Skip to content

Instantly share code, notes, and snippets.

@heymichaelp
Last active August 29, 2015 14:02
Show Gist options
  • Select an option

  • Save heymichaelp/8f898a748cd07831bf59 to your computer and use it in GitHub Desktop.

Select an option

Save heymichaelp/8f898a748cd07831bf59 to your computer and use it in GitHub Desktop.
Form Objects: Example of Validator Object
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