Reputation: 1870
My actual validation looks like:
".write": true,
".validate": "newData.child('name').isString()
&& newData.child('surname').isString()
&& newData.child('age').isNumber()",
However, the age
property is optional. User can fill it or not, depends on his decision.
My case is, how to say to firebase that age
is optional, but if it is there (user fills it) - it has to be a number?
Something like maybe type
in Flow or TypeScript (age?: number
)
Thanks!:)
Upvotes: 1
Views: 623
Reputation: 598728
To make the age optional, move its validation rule down to the specific value you're trying to validate:
".write": true,
".validate": "newData.child('name').isString() && newData.child('surname').isString()"
"age": {
".validate": "newData.isNumber()"
}
The reason this works is that validation rules only fire when the data is present, so the validation on age
only is executed when the age property is present, exactly as you want.
In general I'd recommend to move the type-validations down to the child nodes, and only keep the "these properties must be present" on the higher level:
".write": true,
".validate": "newData.hasChildren(['name', 'surname'])",
"name": {
".validate": "newData.isString()"
},
"surname": {
".validate": "newData.isString()"
},
"age": {
".validate": "newData.isNumber()"
}
"$other": {
".validate": false
}
The last validation above ensure that only the specified properties are ever allowed, so users can't add other data (that your code may not be equipped to handle).
Upvotes: 7