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.

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 1.1.0
    17
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 1.1.0
    17
  • 1.0.0
    0

Package Sidebar

Install

npm i mithril-validator

Weekly Downloads

15

Version

1.1.0

License

MIT

Last publish

Collaborators

  • nijikokun