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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With