Form Validation React
Form Validation React
Form validation in React allows an error message to be displayed if the user has not correctly filled
out the form with the expected type of input.
There are several ways to validate forms in React; however, this shot will focus on creating
a validator function with validation rules.
Open your terminal and execute the following command on your terminal to create a new react app:
To run the React app, execute the following command on your terminal:
>npm start
Execute the following command to install react boostrap library into your react app:
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
function App() {
return (
<div>
</div>
);
}
Create CustomForm.js file. So, visit the src directory of your react js app and create a custom form
validation component file named CustomForm.js. And add the following code into it:
const defaultState = {
name:null,
email:null,
password:null,
nameError:null,
emailError:null,
passwordError:null
constructor(){
super();
this.state = defaultState;
this.handleInputChange = this.handleInputChange.bind(this);
handleInputChange(event) {
this.setState({
[name]: value
});
}
validate(){
if(!this.state.name){
if(!this.state.password){
this.setState({nameError,emailError,passwordError});
return false;
return true;
submit(){
if(this.validate()){
console.warn(this.state);
this.setState(defaultState);
render(){
return(
<div>
<div className="row">
<div className="form-row">
<label>Name :</label>
<span className="text-danger">{this.state.nameError}</span>
</div>
</div>
<div className="form-row">
<label>Email :</label>
<span className="text-danger">{this.state.emailError}</span>
</div>
</div>
<div className="form-row">
<label>Password :</label>
<span className="text-danger">{this.state.passwordError}</span>
</div>
</div>
<div className="form-row">
</div>
</div>
</div>
</div>
</div>
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
function App() {
return (
<div className="App">
<CustomForm />
</div>
);