Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate this data structure with Firebase security rules?

So far not having any luck with Firebase Security rules.

I have this

{
    "rules": {
       "users": {
          "$user_id": {
            ".read": true,
            ".write": "auth !== null && auth.uid === $user_id",
            "profile": {
               ".validate": "newData.hasChildren(['first_name', 'last_name'])"
            }
         }
      }
    }
}

I send data and for the profile and one of them is blank... it lets it write any way. I wind up with data like so...

{
  "users" : {
    "simplelogin:25" : {
       "profile" : {
          "first_name" : "John",
          "last_name" : ""
       }
  },
    "simplelogin:26" : {
      "profile" : {
        "first_name" : "Bob",
        "last_name" : ""
      }
    }
  }
}

Any help on how to make the above rules work? Cant seem to get it to validate correctly.

like image 635
justbane Avatar asked Mar 12 '26 21:03

justbane


1 Answers

Your validation rule is:

".validate": "newData.hasChildren(['first_name', 'last_name'])"

So the new data is valid if it has first_name and last_name properties.

You're sending this object over:

"profile" : {
  "first_name" : "John",
  "last_name" : ""
}

This object has a first_name and a last_name property, so it is valid according to your rule.

What you seem to want is that the properties don't only exist, but also are strings and have a minimum length. If that is indeed your requirement, you can write it into your validation rules:

"profile": {
   ".validate": "newData.hasChildren(['first_name', 'last_name'])",
   "first_name": {
       ".validate": "newData.isString() && newData.val().length >= 10"
   },
   "last_name": {
       ".validate": "newData.isString() && newData.val().length >= 10"
   }
}

The first .validate ensures that a profile has (at least) first_name and last_name properties. The other .validate rules ensure that they are of the correct type and minimum length.

like image 88
Frank van Puffelen Avatar answered Mar 15 '26 10:03

Frank van Puffelen