Skip to content

Instantly share code, notes, and snippets.

@danro
Created July 8, 2014 02:33
Show Gist options
  • Save danro/be0d4290a71e4d21a647 to your computer and use it in GitHub Desktop.
Save danro/be0d4290a71e4d21a647 to your computer and use it in GitHub Desktop.
// 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