Advanced Object Validation
With the composable nature of Strickland, it is very easy to perform advanced object validation. If our person object might be null in the input, we could use required to validate that it isn't null. And since validators are just functions, we could even write a custom validator to ensure that a person named 'Stanford Strickland' must be born in 1925.
import validate, {
objectProps, required, length, range, every
} from 'strickland';
// Define the rules for first name, last name, and birthYear
const personPropsValidator = objectProps({
firstName: every([
required(),
length(2, 20)
]),
lastName: every([
required(),
length(2, 20)
]),
birthYear: range(1900, 2018)
});
function stanfordStricklandBornIn1925(person) {
if (!person) {
// If there's no person provided, return valid and
// rely on `required` to ensure a person exists
return true;
}
const {firstName, lastName} = person;
if (firstName === 'Stanford' && lastName === 'Strickland') {
return (person.birthYear === 1925);
}
return true;
}
const personValidator = every([
required(),
personPropsValidator,
stanfordStricklandBornIn1925
]);
// Create a person
const person = {
firstName: 'Stanford',
lastName: 'Strickland',
birthYear: 1925
};
const result = validate(personValidator, person);In this example, the following will be validated (in this order):
The
personis not emptyThe
personprops are validated:firstNameis not emptyfirstNamehas a length between 2 and 20lastNameis not emptylastNamehas a length between 2 and 20birthYearis between 1900 and 2018
stanfordStricklandBornIn1925is validated
Here are some notes should anything have been invalid:
If the
personwas empty, neither the object props norstanfordStricklandBornIn1925would be validatedIf the
firstNameprop was empty, its length would not be validatedIf the
lastNameprop was empty, its length would not be validatedIf the
firstName,lastName, orbirthYearprops were invalid,stanfordStricklandBornIn1925would not be validated
Last updated
Was this helpful?