Easily validate Mithril.js models, and objects.
- Download the latest package
- NPM:
npm install mithril-validator
var m = require('mithril')
require('mithril-validator')(m)
Validates mithril models and objects through validation functions mapped to specific model properties.
// Our mithril model
var Todo = function (data) {
this.name = m.prop(data.name || '')
this.done = m.prop(data.done)
}
// Initialize a new validator
var validator = new m.validator({
// Check model name property
name: function (name) {
if (!name) {
return "Name is required."
}
}
})
// Results in "Name is required."
validator.validate(new Todo()).hasError('name')
Returns length of error mapping
if (validator.hasErrors()) {
// do something
}
Returns the element associated with the specified key from the error mapping
m('input', {
// Set class to error when an error for this field has occurred
// Trigger validator on submission or when a field changes
class: ctrl.validator.hasError('name') ? 'error' : '',
onchange: m.withAttr('value', ctrl.model.name),
value: ctrl.model.name()
})
Removes all of the elements from the error list.
// Results in "Name is required."
validator.hasError('name')
validator.clearErrors()
// Results in undefined
validator.hasError('name')
Validates the specified model against the validations mapping in this instance.
Each (shallow) property is iterated over and cross-checked against the given model for value, then the validation function is invoked passing the model as context and value as the first argument.
On a truthy result from a validation function the result is placed on the error object with the property name as the identifier.
validator.validate(new Todo())
Note Missing properties are treated as undefined
and do not throw errors, you should do this yourself
within the property validator.
Licensed under The MIT License.