Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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