Last active
September 15, 2016 08:56
-
-
Save parshap/9418694 to your computer and use it in GitHub Desktop.
React input validation
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
/** @jsx React.DOM */ | |
"use strict"; | |
var React = require("react"); | |
// Usage: | |
// <ValidatedInput validateValue={myValidationFunction} | |
// onValidationError={handleError} | |
// valueLink={...} /> | |
module.exports = React.createClass({ | |
getValueLink: function() { | |
var valueLink = this.props.valueLink; | |
var requestChange = valueLink.requestChange.bind(valueLink); | |
var validateValue = this.props.validateValue; | |
var onValidationError = this.props.onValidationError; | |
valueLink.requestChange = function(value) { | |
try { | |
validateValue(value); | |
} | |
catch (err) { | |
return onValidationError(err, value); | |
} | |
requestChange(value); | |
}; | |
return valueLink; | |
}, | |
render: function() { | |
return this.transferPropsTo( | |
<input valueLink={this.getValueLink()} /> | |
); | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment