How to limit (Flutter) string min/max length with security rules in Firebase

You must be checking request.resource.data which contains incoming data and not resource.data which holds existing data from the document. Also try using size() instead of .length to check string length:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{uid} {
      allow read, write, update: if request.auth != null
        && request.auth.uid == userId
        && request.resource.data.username.size() >= 3
        && request.resource.data.username.size() <= 30
        && request.resource.data.undername is string;
    }
  }
}

For example, if current value of username is ‘Jim’ in the document and you are trying to update it to ‘James’, value of resource.data.username.size() would be 3 (length of existing name) and request.resource.data.username.size() would be 5 (length of new name). It’s length of the new name that you are supposed to measure so you need to use request.resource.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top