Validation rules
isNumber
Summary
Sails provides the isNumber
validation rule to ensure that a JSON or ref attribute only contains numbers. This is useful when dealing with attributes that store JSON data but need to restrict values to numeric types.
For example, consider the favoriteFrameworks
attribute:
favoriteFrameworks: {
type: 'json',
isNumber: true
}
This means that only numbers will be accepted, even though JSON can store arrays, objects, strings, or null.
Key takeaways:
isNumber
works only onjson
andref
types.Non-numeric values (like strings) will trigger a validation error.
Useful for ensuring numeric-only JSON values in your model.
If we try to create a user with an invalid value:
await User.create({ favoriteFrameworks: "four" });
Sails will return an error:
"four"
is not a number.
But passing a valid number works fine:
await User.create({ favoriteFrameworks: 4 }); // Success!
This validation rule ensures data consistency by preventing non-numeric values from being stored.
Transcript
All right, so let's look at another validation rule in Sails. I'll open my User model, which we've been using in this course.
Let's say we have a field favoriteFrameworks, which we want to store as a number, even though its type is JSON. Normally, JSON can hold arrays, null, strings, or objects, but we want to restrict it only to numbers.
To do this, we use the isNumber
validation rule:
favoriteFrameworks: {
type: 'json',
isNumber: true
}
This means that although the field is JSON, it will only accept numbers.
Testing the validation rule
I'll open Guppy and try to create a user:
await User.create({ favoriteFrameworks: "four" });
This fails because "four"
is a string:
"four"
is not a valid number.
However, if we pass a valid number:
await User.create({ favoriteFrameworks: 4 });
It works! 🎉
Since we didn’t specify other required fields, they are empty, but our validation ensures only numbers are accepted.
This is a powerful way to enforce data integrity, especially when using JSON fields that should store only numeric values.
Full Course
USD