npm

Don't miss out on this year's npm Pride t-shirt designs!Order your favorites here »

mithril-validator

1.1.0 • Public • Published

Mithril Validator

Easily validate Mithril.js models, and objects.

version License Build Status Downloads Code Climate Coverage Status Dependencies

Install

Setup

var m = require('mithril')
require('mithril-validator')(m)

Documentation

new m.validator(validators) -> Validator

Validates mithril models and objects through validation functions mapped to specific model properties.

Example

// 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')

validator.hasErrors() -> Boolean

Returns length of error mapping

if (validator.hasErrors()) {
  // do something
}

validator.hasError(key) -> Mixed

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()
})

validator.clearErrors() -> void

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')

validator.validate(model) -> Validator

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.

License

Licensed under The MIT License.

install

npm i mithril-validator

Downloadsweekly downloads

6

version

1.1.0

license

MIT

last publish

collaborators

  • avatar
Report a vulnerability