Skip to content

Instantly share code, notes, and snippets.

@nijikokun
Last active May 18, 2016 15:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nijikokun/f39f0ae03a70273da621 to your computer and use it in GitHub Desktop.
Save nijikokun/f39f0ae03a70273da621 to your computer and use it in GitHub Desktop.
Mithril validation utility
m.validator = function (model, validations) {
this.errors = {}
this.validations = validations
this.model = model
}
m.validator.prototype.hasErrors = function () {
return Object.keys(this.errors).length
}
m.validator.prototype.hasError = function (prop) {
return this.errors[prop]
}
m.validator.prototype.clearErrors = function () {
this.errors = {}
}
m.validator.prototype.validate = function () {
var self = this
this.clearErrors()
Object.keys(this.validations).forEach(function (key) {
var validator = self.validations[key]
var value = self.model[key]()
var result = validator.bind(self.model)(value)
if (result) {
self.errors[key] = result
}
})
return self
}
@iamjohnlong
Copy link

Can you show an example of how you should use this? Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment