Last active
August 29, 2015 14:02
-
-
Save heymichaelp/8f898a748cd07831bf59 to your computer and use it in GitHub Desktop.
Form Objects: Example of Validator Object
This file contains hidden or 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
| var _ = require('underscore') | |
| var NewStudentFormValidator = function() { | |
| this.errors = [] // for storing validation errors encountered | |
| } | |
| NewStudentFormValidator.prototype = _.extend(NewStudentFormValidator.prototype, { | |
| validate: function(data) { | |
| // call each validation method, storing | |
| // any errors on the this.errors array | |
| _.compose( | |
| this.validateFirstName, | |
| this.validateLastName, | |
| ).call(this, data) | |
| return this | |
| }, | |
| // predicate identifying valid status | |
| // based on this.errors.length | |
| isValid: function() { | |
| return this.errors.length === 0 | |
| }, | |
| validateFirstName: function(data) { | |
| if (_.isUndefined(data.firstName)) { | |
| this.errors.push(new Error('first name is required')) | |
| } | |
| return data | |
| }, | |
| validateLastName: function(data) { | |
| if (_.isUndefined(data.lastName)) { | |
| this.errors.push(new Error('last name is required')) | |
| } | |
| return data | |
| } | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment