Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate that value is an Integer with Firebase rules

I'm trying to make sure that some field of an object in firebase is an integer and not decimal. There is a method isNumber() but it returns true wheter value is an integer or a decimal.

I've tried to check a value with regex, but for some reason it works properly only with values within quotation marks ie strings.

This is how my rule looks:

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

So when I put an object with string value like this {"created":"123456789"} validation works fine. But when I put an object with number value {"created":123456789} validation fails.

Is there a way to do this?

like image 253
dzikovskyy Avatar asked Feb 04 '23 06:02

dzikovskyy


1 Answers

You cannot use a regular expression to validate a number, since regular expressions match patterns in strings.

You can also not really validate that something is an integer, since JavaScript doesn't have a separate integer vs floating point type. They're all just floating point numbers.

What you can validate is that something is a whole number. The simplest way I could come up with is:

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

This accepts 1 and 1.0, but will reject 1.1.

like image 149
Frank van Puffelen Avatar answered Feb 07 '23 11:02

Frank van Puffelen