Created
April 16, 2014 18:27
-
-
Save cly/10917256 to your computer and use it in GitHub Desktop.
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
// validation mixin | |
var validation = { | |
getDefaultProps: function () { | |
return { | |
validate: [] | |
} | |
} | |
, hasErrors: function () { | |
var errors = [] | |
this.props.validate.forEach(function (condition) { | |
if (condition.test(this.state.value)) | |
errors.push(condition.message) | |
}) | |
return errors.length ? errors : false | |
} | |
} | |
var Input = React.createClass({ | |
mixins: [validation] | |
, getInitialState: function () { | |
return { | |
value: this.props.value | |
} | |
} | |
, componentWillReceiveProps: function (props) { | |
this.setState({ value: props.value }) | |
} | |
, onChange: function (event) { | |
var errors = this.hasErrors() | |
if (errors) { | |
// handle invalid format | |
// show error messages | |
} | |
else { | |
this.setState({ value: event.target.value }) | |
} | |
} | |
, render: function() { | |
var settings = { | |
value: this.state.value | |
, onChange: this.onChange | |
} | |
return React.DOM.input(settings) | |
} | |
}) | |
// an array of conditions to test agains | |
var conditions = [{ | |
test: function (value) { return value !== '' } | |
, message: 'Field cannot be empty' | |
}, { | |
test: function (value) { return value.length <= 140 } | |
, message: 'Field should not have more than 140 characters' | |
}] | |
var input = Input({ validate: conditions }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment