Validation rules
Custom validation rules
Summary
Aside from using regex for validation, Sails also allows custom validation functions. These functions take a value and return true
(valid) or false
(invalid), making them highly flexible for unique business rules.
Transcript
For example, suppose your app is only available in Nigeria, Kenya, and Ghana. You can enforce this rule using a custom validation function.
Example: Restricting Signups to Specific Countries
In your Sails model, define the country
attribute like this:
country: {
type: 'string',
custom: (value) => ['Nigeria', 'Kenya', 'Ghana'].includes(value),
}
Key takeaways:
✅ Custom validation functions allow more flexibility than built-in rules.
✅ The function receives the value and must return true
or false
.
✅ Works for all data types (string, number, JSON, boolean, etc.).
Testing the Validation Rule
1. Invalid Country
await User.create({ country: "Uganda" });
❌ Fails, because Uganda is not in the allowed list.
2. Valid Country
await User.create({ country: "Nigeria" });
✅ Passes, because Nigeria is in the allowed list.
3. Testing All Allowed Countries
await User.create({ country: "Kenya" }); // ✅ Passes
await User.create({ country: "Ghana" }); // ✅ Passes
When to Use custom
Validation
Business logic rules (e.g., allowed countries, age limits, company-specific validation).
More complex conditions (e.g., cross-field validation, checking external APIs).
Fallback when built-in rules are insufficient.
Next Up:
When to use validation rules
Full Course
USD