Validation rules
max
Summary
In Sails.js, use the max
validation rule to enforce a maximum value for attributes with the number
data type. Combined with the min
rule, you can define a valid range for values.
For example, setting min: 18
and max: 120
ensures the age
attribute only accepts values between 18
and 120
(inclusive). This prevents invalid inputs like 2
or 2000
while allowing valid values within the specified range.
Transcript
Now that we’ve set a minimum value for the age
attribute, let’s explore how to set a maximum value. In the previous lesson, we ensured age
must be at least 18
. However, without a maximum, users could input unrealistic values like 2000
.
To fix this, add the max
validation rule:
age: {
type: 'number',
defaultsTo: 18,
min: 18,
max: 120
}
This ensures age
must be between 18
and 120
(inclusive).
Testing the Validation:
Invalid Input (Below Minimum):
await User.create({ age: 2 });
Error:
"Value 2 was less than the configured minimum (18)."
Invalid Input (Above Maximum):
await User.create({ age: 2000 });
Error:
"Value 2000 was greater than the configured maximum (120)."
Valid Input (Within Range):
await User.create({ age: 120 }); await User.create({ age: 50 });
Result: Records are created successfully.
Key Takeaways:
Use
max
to enforce a maximum value fornumber
attributes.Combine
min
andmax
to define a valid range for values.This ensures data integrity by preventing unrealistic or invalid inputs.
Full Course
USD