Validation rules
minLength
Summary
In Sails.js, use the minLength
validation rule to enforce a minimum character length for string attributes. This ensures that values like firstName
or password
meet a specified length requirement (e.g., at least 2 characters). If the input is shorter than the configured minimum, the validation fails, preventing invalid data from being saved.
Transcript
Oftentimes, you might want to set a minimum length for a string. For example, you may want a string to be at least a specific number of characters long. While you could handle this in your business logic, Sails provides a built-in validation rule called minLength
to simplify this process.
Let’s apply this to the firstName
attribute. Suppose we want firstName
to be at least 2 characters long. Here’s how you can configure it:
firstName: {
type: 'string',
minLength: 2
}
This ensures that firstName
must be 2 characters or longer.
Testing the Validation:
Invalid Input (Too Short):
await User.create({ firstName: 'K' });
Error:
"Value 'K' was shorter than the configured minimum length (2)."
Valid Input (Meets Minimum Length):
await User.create({ firstName: 'Ari' });
Result: The record is created successfully.
Use Cases:
Enforce minimum lengths for attributes like
firstName
,lastName
, orpassword
.Ensure data quality by preventing overly short or invalid inputs.
This is how you use the minLength
validation rule in Sails to set a lower bound for string attributes.
Full Course
USD