Last active
May 2, 2019 20:29
-
-
Save verdi327/71c60a05b998dabb4d96cfaf37fbda13 to your computer and use it in GitHub Desktop.
form-validation-example-1
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
//Step One - set state | |
state = { | |
username: '', usernameValid: false, | |
formValid: false, | |
errorMsg: {} | |
} | |
// Step Two Part A - Add onChange to form field (inside your render fn) | |
<div className='form-group'> | |
<label htmlFor='username'>Username</label> | |
< ValidationMessage valid={this.state.usernameValid} message={this.state.errorMsg.username} /> | |
<input type='text' id='username' name='username' className='form-field' | |
value={this.state.username} onChange={(e) => this.updateUsername(e.target.value)}/> | |
</div> | |
// Step Two Part B: onChange handler calls this method | |
updateUsername = (username) => { | |
this.setState({username}, this.validateUsername) | |
} | |
// Step Three: Validate the username after we save it to state | |
validateUsername = () => { | |
const {username} = this.state; | |
let usernameValid = true; | |
let errorMsg = {...this.state.errorMsg} | |
if (username.length < 3) { | |
usernameValid = false; | |
errorMsg.username = 'Must be at least 3 characters long' | |
} | |
this.setState({usernameValid, errorMsg}, this.validateForm) | |
} | |
// Step Four: Validate the form based field inputs (right now we only are validating username) | |
validateForm = () => { | |
const {usernameValid} = this.state; | |
this.setState({ | |
formValid: usernameValid | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment