Last active
July 21, 2016 16:30
-
-
Save ftorre104/00e7191391bb63304a4404d8c19c7518 to your computer and use it in GitHub Desktop.
Form validation in react -- 2 options
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
// OPTION A | |
// Handle error/help display logic at the input's parent level | |
submit() { | |
this.setState({ | |
emailHasBeenBlurred: true, | |
pwHasBeenBlurred: true | |
}) | |
if (validator.email(this.state.value).help || | |
validator.pw(this.state.value).help ) { | |
return false; | |
} | |
// ... submit form | |
} | |
... | |
<InputGroup | |
value={this.state.email} | |
onBlur={() => this.setState({emailHasBeenBlurred: true})} | |
help={this.state.emailHasBeenBlurred ? validator.email(this.state.value).help : ''} | |
> | |
<InputGroup | |
value={this.state.email} | |
onBlur={() => this.setState({pwHasBeenBlurred: true})} | |
help={this.state.pwHasBeenBlurred ? validator.email(this.state.value).help : ''} | |
> | |
<button onClick={this.submit} /> | |
... | |
// OPTION B | |
// Handle error/help display logic at the input's state level | |
// Each input has a `shouldShowError` state, which activates onBlur. | |
// On willReceivePRop, the `forceShowError` results in activating the input's `shouldShowError` state | |
submit() { | |
this.setState({ | |
formSubmitted: true | |
}) | |
if (validator.email(this.state.value).help || | |
validator.pw(this.state.value).help) { | |
return false; | |
} | |
// ... submit form | |
} | |
... | |
<InputGroup | |
value={this.state.email} | |
forceShowError={this.state.formSubmitted} | |
help={validator.email(this.state.value).help} | |
> | |
<InputGroup | |
value={this.state.pw} | |
forceShowError={this.state.formSubmitted} | |
help={validator.pw(this.state.value).help} | |
> | |
<button onClick={this.submit} /> | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment