Last active
May 18, 2016 15:11
-
-
Save nijikokun/f39f0ae03a70273da621 to your computer and use it in GitHub Desktop.
Mithril validation utility
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you show an example of how you should use this? Thanks!