Validate a Firebase Key is an integer

前端 未结 2 690
后悔当初
后悔当初 2021-01-05 23:41

Here is the database schema:

Here are the rules:

\"notifications\": {
   \"$year\": {
      \".read\": \"false\",
      \".write\": \"!data.         


        
相关标签:
2条回答
  • 2021-01-06 00:24

    To validate that a key is a number:

    {
      "$key": {
         ".validate": "$key.matches(/^[0-9]+$/)"
      }
    }
    

    But please read about array-like behaviors in Firebase. Hint: probably use a prefix like "y2015", "m12", etc. to avoid some unexpected results with using numbers.

    0 讨论(0)
  • 2021-01-06 00:26

    If using push IDs works for you, here's a security rule structure you could use.

    {
        "notifications": {
            "$notification_id": {
                ".write": "!data.exists()",
                ".read": "false",
                ".validate": "newData.hasChildren(['time', 'state', 'message'])",
                "time": {
                    ".validate": "newData.val().matches(/YOUR REGEX/)"
                },
                "state": {
                    ".validate": ""
                },
                "message": {
                    ".validate": ""
                }
            }
        }
    }
    

    Obviously you'll need to fill in the blanks. The main thing here is that you can use a regex to match the time field.

    The actual data would look like:

    {
        "notifications": {
            "-K-z5koYf8mYZu5OfSGR": {
                "time": "2015-10-06-17-30",
                "state": 1,
                "message": "foo"
            },
            "-K-z5koYf8mYZwgwsfGx": {
                "time": "2015-10-06-17-30",
                "state": 1,
                "message": "bar"
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题