Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ninadvadujkar/80847f94beb3f0d9bfba40fd114a38ae to your computer and use it in GitHub Desktop.
Save ninadvadujkar/80847f94beb3f0d9bfba40fd114a38ae to your computer and use it in GitHub Desktop.
HTML5 Validation with React.
import React, { Component } from 'react';
class FormTest extends Component {
constructor(props) {
super(props);
this.state = {
username: {
value: '',
valid: false,
errorMessage: ''
},
password: {
value: '',
valid: false,
errorMessage: ''
},
form: {
valid: false
}
}
}
onInputChange(event) {
const targetName = event.target.name;
const targetValue = event.target.value;
const el = this.refs[targetName];
this.setState({
[targetName]: {
value: targetValue,
valid: el.validity.valid,
errorMessage: el.validity.valueMissing ? `${targetName} is required` : el.validationMessage
},
form: {
valid: this.form.checkValidity()
}
});
}
onSubmit(event) {
}
returnErrorMessage(inputType) {
let obj = this.state[inputType];
return (
<span>
{!obj.valid && obj.errorMessage}
</span>
);
}
render() {
return (
<div>
<div>Form Test</div>
<form onSubmit={this.onSubmit.bind(this)} ref={form => this.form = form}>
<input ref='username' type="text" value={this.state.username.value} onChange={this.onInputChange.bind(this)} name='username' required/>
{this.returnErrorMessage('username')}
<br/><br/>
<input ref='password' type="password" value={this.state.password.value} onChange={this.onInputChange.bind(this)} name='password' required/>
{this.returnErrorMessage('password')}
<br/><br/>
<button type="submit" disabled={!this.state.form.valid}>Submit</button>
</form>
</div>
);
}
}
export default FormTest;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment