Maiken Madsen
Maiken Madsen

Reputation: 651

Validation in Firebase Rules

I got a JSON data structure like this:

recipes
   LZogi4JdMk_V5vLK_aA
       title: 'firste recipe'
   LZoh4QphqHknuvda0-f
       title 'secound recipe'

I want to make a rule (validation) for the title in each recipe. I have tried doing this:

"rules": {
  "recipes": {
    ".write": "auth != null",
    ".read": "auth != null", 
   "$title": {
        ".validate": "newData.isString() 
             && newData.val().length > 0
             && newData.val().length <= 20"
  }
}

I think I have to get into each object in the array recipe but i'm not sure. Can anybody help?

Upvotes: 1

Views: 77

Answers (1)

itstrevino
itstrevino

Reputation: 116

According to firebase docs and samples $ is used to represent ids and dynamic child keys, currently you are treating $title as if it was the ID of each recipe, so your rules should instead look something like this:

"rules": {
  "recipes": {
    ".write": "auth != null",
    ".read": "auth != null",
    "$recipeId": {    //example: LZogi4JdMk_V5vLK_aA
      "title": {
        ".validate": "newData.isString() 
             && newData.val().length > 0
             && newData.val().length <= 20"
      }
    }
  }

Here's the link to firebase docs: https://firebase.google.com/docs/database/security/securing-data#structuring_your_rules

Upvotes: 1

Related Questions