Last active
August 29, 2015 14:02
-
-
Save heymichaelp/10718b947bf177dbffbe to your computer and use it in GitHub Desktop.
Form Objects: Example of Complete Form 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 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