Gibran Shah
Gibran Shah

Reputation: 1109

How to limit string length in firebase

I working in a firebase database. I need to limit the length of a string field. How do I do that?

The path to the field is:

Col1/doc1///description

That is, starting with the collection col1, then into doc1, then for all collections under doc1, and all documents under that collection, the description field needs to be limited to 100 characters.

Can someone please explain to me how to do this? Thanks

Upvotes: 11

Views: 5837

Answers (3)

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

For Cloud Firestore you can validate that the description field is no longer than 100 characters with:

service cloud.firestore {
  match /databases/{database}/documents {
    match /col1/doc1 {
      allow write: if resource.data.description.size() <= 100;

        match /subcollection1/{doc=**} {
          allow  write: if resource.data.description.size() <= 100;
        }
    }
  }
}

This applies to col1/doc and all documents in subcollection1. Note that these rules will not limit the length of the description, since security rules cannot modify the data that is written. Instead the rules reject writes where the description is longer than 100 characters.

There is no way (that I know of) to apply rules to each subcollection of only one document. The closest I know is to apply it to all documents and their subcollections:

match /col1/(document=**} {
  allow write: if resource.data.description.size() <= 100;
}

This applies the validation to all documents in col1 and in all subcollections under that.

Upvotes: 4

nCr78
nCr78

Reputation: 480

On the Firebase documentation, for Firestore specifically, it seems that you can use the Map interface's get() function.

For example:

service cloud.firestore {
    match /databases/{database}/documents {
        match /{document=**} {
            allow read: if true;
            allow write: if request.resource.data.get('description', '').size() < 256;
        }
    }
}

Documentation as of Feb 2023 can be found here

Upvotes: 0

RoboKozo
RoboKozo

Reputation: 5062

I tried to get the validation from the other answer to work but was unsuccessful. Firestore just doesn't like checking .length on resource data values.

I searched around and this article helped me: https://fireship.io/snippets/firestore-rules-recipes/

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
      match /posts/{postId} {
        allow read: if true;
        allow write: if request.auth != null 
                     && request.auth.uid == request.resource.data.uid
                     && request.resource.data.body.size() > 0
                     && request.resource.data.body.size() < 255
                     && request.resource.data.title.size() > 0
                     && request.resource.data.title.size() < 255;
      }
  }
}

Upvotes: 18

Related Questions