In this article, we will discuss the form-validation in React.js. Since we all come across forms to send data to the server and its needed to validate input from the user. So that desired value can be submitted from the form. Html provides the basic level of form-validation. There are also many NPM packages available to validate the form in React.js form. So let's start how form can be validated by React.js.
create a very basic app of react.js by using below command over terminal.
For the form validation task, We will use validator package of NPM. Install it by typing below command:
Create a file inside src folder named, FormValidator.js. And put the below code inside it.
import validator from 'validator';
class FormValidator {
constructor(validations) {
this.validations = validations;
}
validate(state) {
let validation = this.valid();
// for each validation rule
this.validations.forEach(rule => {
if (!validation[rule.field].isInvalid) {
const field_value = state[rule.field].toString();
const args = rule.args || [];
const validation_method =
typeof rule.method === 'string' ?
validator[rule.method] :
rule.method
if(validation_method(field_value, ...args, state) !== rule.validWhen) {
validation[rule.field] = { isInvalid: true, message: rule.message }
validation.isValid = false;
}
}
});
return validation;
}
valid() {
const validation = {}
this.validations.map(rule => (
validation[rule.field] = { isInvalid: false, message: '' }
));
return { isValid: true, ...validation };
}
}
export default FormValidator;
In the above class, I have defined validation rules.
Open the App.js file and put the below code in it.
import React, {Component} from 'react';
import FormValidator from './FormValidator';
import './App.css';
class App extends Component{
constructor(){
super();
this.validator = new FormValidator([
{
field: 'full_name',
method: 'isEmpty',
validWhen: false,
message: 'Enter full name.'
},
{
field: 'email',
method: 'isEmpty',
validWhen: false,
message: 'Enter your email address.'
},
{
field: 'email',
method: 'isEmail',
validWhen: true,
message: 'Enter valid email address.'
},
{
field: 'phone',
method: 'isEmpty',
validWhen: false,
message: 'Enter a phone number.'
},
{
field: 'phone',
method: 'matches',
args: [/^\(?\d\d\d\)? ?\d\d\d-?\d\d\d\d$/],
validWhen: true,
message: 'Enter valid phone number.'
},
{
field: 'password',
method: 'isEmpty',
validWhen: false,
message: 'Enter password.'
},
{
field: 'password_confirmation',
method: 'isEmpty',
validWhen: false,
message: 'Enter Password confirmation.'
},
{
field: 'password_confirmation',
method: this.passwordMatch, // notice that we are passing a custom function here
validWhen: true,
message: 'Password and password confirmation do not match.'
}
]);
this.state = {
full_name: '',
email: '',
phone: '',
password: '',
password_confirmation: '',
validation: this.validator.valid(),
}
this.submitted = false;
}
passwordMatch = (confirmation, state) => (state.password === confirmation)
handleInputChange = event => {
event.preventDefault();
this.setState({
[event.target.name]: event.target.value,
});
}
handleFormSubmit = event => {
event.preventDefault();
const validation = this.validator.validate(this.state);
this.setState({ validation });
this.submitted = true;
if (validation.isValid) {
//reaches here if form validates successfully...
}
}
render() {
let validation = this.submitted ?this.validator.validate(this.state) : this.state.validation
return (
<div className="container">
<div className="row">
<div className="col-md-4 col-md-offset-4">
<form className="registrationForm">
<h2>Registration form</h2>
<div className={validation.email.isInvalid && 'has-error'}>
<label htmlFor="full_name">Full Name</label>
<input type="string" className="form-control"
name="full_name"
placeholder="Full Name"
onChange={this.handleInputChange}
/>
<span className="help-block">{validation.full_name.message}</span>
</div>
<div className={validation.email.isInvalid && 'has-error'}>
<label htmlFor="email">Email address</label>
<input type="email" className="form-control"
name="email"
placeholder="Email address"
onChange={this.handleInputChange}
/>
<span className="help-block">{validation.email.message}</span>
</div>
<div className={validation.phone.isInvalid && 'has-error'}>
<label htmlFor="phone">Phone(enter only 10 digit number)</label>
<input type="phone" className="form-control"
name="phone"
placeholder="Phone Number"
onChange={this.handleInputChange}
/>
<span className="help-block">{validation.phone.message}</span>
</div>
<div className={validation.password.isInvalid && 'has-error'}>
<label htmlFor="password">Password</label>
<input type="password" className="form-control"
placeholder="Password"
name="password"
onChange={this.handleInputChange}
/>
<span className="help-block">{validation.password.message}</span>
</div>
<div className={validation.password_confirmation.isInvalid && 'has-error'}>
<label htmlFor="password_confirmation">Confirm Password</label>
<input type="password" className="form-control"
placeholder="Confirm Password"
name="password_confirmation"
onChange={this.handleInputChange}
/>
<span className="help-block">{validation.password_confirmation.message}</span>
</div>
<button onClick={this.handleFormSubmit} className="btn btn-primary">
Register
</button>
</form>
</div>
</div>
</div>
)
}
}
export default App;
So in this demo, We learn to do form validation in React.js. You can find other demos of React.js Sample Projects here.
That’s all for now. Thank you for reading and I hope this demo will be very helpful to do form validation in React.js application.
Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.