value-validator
Low-level rule manager for validating values.
Install
$ npm install value-validator --save
Usage
const Validator = const validator = /.{4,}/ /^[a-z0-9_]+$/i { return } validator // Examplesvalidator validator validator
new Validator(rule, options)
- rule
RegExp|function()|String|Array.<mixed>
rule could be- regular expression,
- function either returns a
Promise
or normal value - string (validator preset),
- or an array of mixed-type of the former three.
.validate(value [, callback])
- value
any
value to be validated - callback
function(err, pass)=
using callback is deprecated since2.2.0
, and the parameter will be removed in the next major version.
returns a Promise
if no callback
, or undefined
.context(context)
- context
Object
specify this object for all validator functions.
Returns this
rule
Sync Function-type The function should accept only one argument, which is the value to be validated.
If the function returns a Boolean
, it indicates whether the validation is passed, and the err
will be null
const validator = v > 10validator
If the function returns an Error
, it means the validation fails, and the error will passed to the callback function of validate(v, callback)
as the first parameter err
.
const validator = { if v > 10 return true return 'should larger than 10'}validator
Async validator
To define an asynchronous validator, just returns a Promise
.
Validator.defaults({preset=, codec=})
Pre-defines certain option of Validator
and returns a constructor.
Validator presets are an abbreviation of a certain validation, or a set of validations.
const presets = // To define a function-typed preset { return { } } min4: /.{4,}/ // A preset could be a set of presets. username: 'min4' /^[a-z0-9_]+$/i 'unique' const MyValidator = Validator // Then we could use `username` as the test rule.const validator = 'username'
License
MIT