A plugin that adds validators to a model.
$ component install component/model-validate
var model = require('model');
var validate = require('model-validate');
var isEmail = require('is-email');
var isUrl = require('is-url');
/**
* User model.
*/
var User = model()
.use(validate())
.attr('id')
.attr('email', { validators: [isEmail] })
.attr('website', { validators: [isUrl] });
/**
* Usage...
*/
var user = new User({ email: 'invalid' });
var valid = user.validate();
if (!valid) {}
var error = user.errors[0];
throw new Error('invalid attribute "' + error.attr + '"');
}
Register a validator fn
. It can be either:
- attribute specific - passing an
attr
, in which case it will be called with the value ofattr
. Attribute-specific validators can also be specified by just adding avalidators
property to an attribute's options. - global - omitting the
attr
, in which case it will be called with the model itself.
Validate the model, returning a boolean of its validity, and populating model.errors
for each failed validation.
Mark an attr
as invalid, with a message
and optional extra context
.