Jabba Da Hoot
Jabba Da Hoot

Reputation: 804

Firebase validate rule regex not working

I cannot get this to work in the Firebase Simulator and I don't understand why. I am making a "favorite" button on my page with a counter that keeps track of the amount of times it was favorited. I want to store the amount in the firebase database. So here are my rules:

{
  "rules": {
    "favorited": {
      ".validate": "newData.isNumber() && newData.val().matches(/[0-9]/) && newData.val().length < 10",
      ".read": true,
      ".write": true
    }
  }
}

Writes should be a integer which can only contain 0 to 9 and be less than 10 characters.

I've tested it with the following JSON data on the following path:

/favorited/

--

{
  "foo": 123
}

This gives a write error on the validation. What am I doing wrong?

Upvotes: 0

Views: 688

Answers (1)

cartant
cartant

Reputation: 58430

The problem is that you're using a regular expression on a number, not a string. And numbers don't have a length property, either.

From the documentation:

Regular expression literals can be used to validate client supplied strings. Use string.matches(/pattern/) to test if a string adheres to a regular expression pattern.

You could use:

newData.isNumber() && newData.val() < 1000000000

As 1000000000 is the smallest number with 10 digits in it.

Upvotes: 2

Related Questions