validator
A function that validates a value against predefined constraints and returns validation errors, if any are found.
validator(value)
function (value) {
if (typeof value === 'undefined' || value === '')) {
return 'is required';
}
}
Parameters
- value
{*}
:A simple value to validate
Returns
{Error|String|undefined|Array<Error|String>}
:
Returns undefined if no errors found. Otherwise, will return an error type with the error message.
Creating a validator
Given that a required
validation exists
// Custom required check
var checkRequired = function (val) {
if (typeof value === 'undefined' || value === '') {
return false;
}
return true;
};
Typically a validator can be created like so
// Validator factory
var makeValidator = function (constraints) {
return function (value) {
if (constraints.required && !checkRequired(value)) {
return 'is required';
}
}
};
Now, creating a validator for any value is possible by doing
var nameValidator = makeValidator({required: true});
Which then allows validating values as needed
nameValidator('Juan'); //> undefined
nameValidator(); //> 'is required'
Validator Response
The response should match the Errors type. The most flexible response is the Error type which describes the error message any value keys that triggered the error state.