Skip to content

Instantly share code, notes, and snippets.

@heymichaelp
Last active August 29, 2015 14:02
Show Gist options
  • Save heymichaelp/10718b947bf177dbffbe to your computer and use it in GitHub Desktop.
Save heymichaelp/10718b947bf177dbffbe to your computer and use it in GitHub Desktop.
Form Objects: Example of Complete Form Object
var _ = require('underscore')
var NewStudentForm = function(data) {
this.data = data
this.errors = [] // for storing validation errors encountered
}
NewStudentForm.prototype = _.extend(NewStudentForm.prototype, {
process: function() {
if (this.isValid()) {
this.persist() // only persist if data is valid
}
return this
},
isValid: function() {
// perform all validations, and store
// errors if validations fail
if (_.isUndefined(this.data.firstName)) {
this.errors.push(new Error('first name is required'))
}
if (_.isUndefined(this.data.lastName)) {
this.errors.push(new Error('last name is required'))
}
// ...
// return boolean representing if
// any errors were encountered during validation
return this.errors.length === 0
},
persist: function() {
// off-load persistence to a service object
return new CreateNewStudent(this.data).run()
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment