-
-
Save captainill/a93247d68c07c479e7b9 to your computer and use it in GitHub Desktop.
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
define(function () { | |
'use strict'; | |
var _ = require('underscore'); | |
var ValidationMixin = { | |
getInitialState: function () { | |
return { | |
errors: [] | |
}; | |
}, | |
componentWillMount: function () { | |
this.assertValidatorsDefined(); | |
}, | |
assertValidatorsDefined: function () { | |
if (!this.validators) { | |
throw new Error('ValidatorMixin requires this.validators to be defined on the component.'); | |
} | |
_.each(_.keys(this.validators), function (key) { | |
var validator = this.validators[key]; | |
if (!_.has(this.state, key)) { | |
throw new Error('Key "' + key + '" is defined in this.validators but not present in initial state.'); | |
} | |
if (!_.isFunction(validator)) { | |
throw new Error('Validator for key "' + key + '" is not a function.'); | |
} | |
}, this); | |
}, | |
hasError: function (key) { | |
return _.contains(this.state.errors, key); | |
}, | |
resetError: function (key) { | |
this.setState({ | |
'errors': _.without(this.state.errors, key) | |
}); | |
}, | |
validate: function () { | |
var errors = _.filter(_.keys(this.validators), function (key) { | |
var validator = this.validators[key], | |
value = this.state[key]; | |
return !validator(value); | |
}, this); | |
this.setState({ | |
'errors': errors | |
}); | |
return _.isEmpty(errors); | |
} | |
}; | |
return ValidationMixin; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment