How to check this value as integer with Firebase rules

I am trying to make sure that any field of an object in firebase is integer and not decimal. There is an isNumber () method , but it returns the true wheter value - integer or decimal.

I tried to check the value using a regex, but for some reason it only works correctly with quoted values, i.e. strings.

This is what my rule looks like:

"$item_id":{
    "created":{
    ".validate":"newData.val().matches(/^[0-9]+$/)"
    }
}  

      

So when I put in an object with a string value like this, the validation {"created":"123456789"}

works fine. But when I put the object with the number value {"created":123456789}

, the validation fails.

Is there a way to do this?

+3


source to share


1 answer


You cannot use a regex to test for a number, since regex matches patterns in strings.

You also can't really check that something is an integer, since JavaScript doesn't have a separate integer or floating point type. They are just floating point numbers.

What you can check is that something is an integer. The easiest way I could think of is:



".validate":"newData.isNumber() && newData.val() % 1 === 0.0" 

      

It accepts 1

and 1.0

but rejects 1.1

.

+4


source







All Articles