Niggle is a tiny, customizable javascript value validator with laravel inspired syntax and no dependencies.
Install using npm install @zipavlin/niggle
const niggle = require('@zipavlin/niggle');
const validate = new Niggle({
// optional options
messages: {
min: 'Your input is too low! Is should be higher than {{options}}'
}
}).validate;
console.log(validate('min:2|max:5', 3));
Validator has only few public methods:
- validate(String validator, String|Int input) - validate input agains validator string and return validity and errors: {valid: Bool, errors: Array|null }
- valid(String validator, String|Int input) - validate input agains validator string and return validity: Bool
- errors(String validator, String|Int input) - validate input agains validator string and return array of errors: Array|null
- registerValidators(Array validators) - register validators
- registerPlugins(Array plugins)
Name | Options | Example | Description |
---|---|---|---|
min | Number | 'min:5' | length (of string) or amount (for number) must be higher than option |
max | Number | 'max:5' | length (of string) or amount (for number) must be lower than option |
between | Number,Number | 'between:1,5' | length (of string) or amount (for number) must be between first option and second option |
length | Number | 'length:5' | length (of string) or amount (for number) must be equal to option |
Null | 'email' | input must match email pattern | |
is | Number/String | 'is:"must be this"' | input must be equal to option (type included) |
pattern | Pattern | 'pattern:^\d{2}$' | input must match pattern |
Validator is basically an object with required name, message and callback properties:
const customValidator = {
name: 'min_or_equal', // required - is used as validator key.
synonym: 'gte', // optional
type: 'number', // optional - is passed to callback. Can be: string, number, range, array
message: 'Input must be higher or equal to {{options}}', // required -- default error message with value injection. Possible dynamic values include options (including arrays), type, input
callback: (input, options, type) => { // required
return isNaN(input) ? (input.length >= options) : (input >= options);
}
}
const validator = new Validator();
validator.registerValidators(customValidator);
validator.validate('min_or_equal:19', 'this is test string'); // true
Plugins are not supported in this moment, but are planned.