Validate a form manually in React Js
If there is a form in our app, it is necessary to validate it. We have to check if all the fields are correctly filled. This saves us from a lot of problems in the future and also saves our time. In this tutorial, we will create a controlled component– a form having states that will store everything the user types.
You can go through this link to know how to create forms in React Js.
How to validate a form in React Js?
There are two ways to validate a form. First, perform validation as the user types. Second, performing validation after the user submits the form.
Let’s go through the first case first. We will have to write the code in the onChange event handler for performing validation as the user types. Look at the code below.
import React, { Component } from 'react' class App extends Component { constructor(props){ super(props); this.state={name:'',age:0,errorName:''}; } handleSubmit=(e)=>{ alert('Your name is: '+this.state.name +'\nYour age is: '+this.state.age); } handleChange=(e)=>{ const name=e.target.name; const value=e.target.value; let error=''; if (name==="name" && value.trim()===''){ error=<strong style={{color:'red'}}>*{name} is required</strong>; } if(name==="age" && this.state.name.trim()===''){ error=<strong style={{color:'red'}}>*Name is required</strong>; } this.setState({errorName:error}); this.setState({ [name]:e.target.value }); } render() { return ( <form onSubmit={this.handleSubmit}> <fieldset> <label for="name">Enter your name: </label> <input type="text" id="name" name="name" onChange={this.handleChange} /> {this.state.errorName} <br/><br/> <label for="age">Enter your age: </label> <input type="number" id="age" name="age" onChange={this.handleChange}/><br/><br/> <button>Submit</button> </fieldset> </form> ) } } export default App
This code continues from the previous post whose link is provided above. Notice that in line no. 14, we create a local variable error and perform two validations for now. First, we check if the field is empty in line no. 15. If it is true then we set our error variable and put an error message there. Second in line no. 18, we check if the user has moved on to the age field without entering a name. If this is true, then we provide an error message that a Name is required. Following this, we update our state variable errorName using setState. We showed this state variable in line no. 34 after the input element. Since we are writing javascript, we include it within curly brackets. Also, note how we used inline style to make the text color red.
The output would look like this:
So this was our validation on the name field. Now we will perform validation on the age field. Since we want our age error message to be displayed along with the age field, we will have to create another state variable errorAge.
We will check that the age should be greater than 0. For that, we will create another local variable – errors and store the error message there. Again we will use setState to update the state and print our state after the input element as shown below.
import React, { Component } from 'react' class App extends Component { constructor(props){ super(props); this.state={name:'',age:0,errorName:'',errorAge:''}; } handleSubmit=(e)=>{ alert('Your name is: '+this.state.name +'\nYour age is: '+this.state.age); } handleChange=(e)=>{ const name=e.target.name; const value=e.target.value; let error='',errors=''; if (name==="name" && value.trim()===''){ error=<strong style={{color:'red'}}>*{name} is required</strong>; } if(name==="age" && this.state.name.trim()===''){ error=<strong style={{color:'red'}}>*Name is required</strong>; } if (value<=0){ errors=<strong style={{color:'red'}}>*Age should be greater than 0</strong>; } this.setState({errorName:error,errorAge:errors}); this.setState({ [name]:value }); } render() { return ( <form onSubmit={this.handleSubmit}> <fieldset> <label for="name">Enter your name: </label> <input type="text" id="name" name="name" onChange={this.handleChange} /> {this.state.errorName} <br/><br/> <label for="age">Enter your age: </label> <input type="number" id="age" name="age" onChange={this.handleChange}/> {this.state.errorAge} <br/><br/> <button>Submit</button> </fieldset> </form> ) } } export default App
We are performing the validation in line no. 23. Notice the changes in lines 26 and 45.
The output would look like this:
Now we just have to perform a check while submitting the form. If there are errors in the form then we should not be able to submit the form. Otherwise, we should be able to submit the form. For that, we will edit the handleSubmit function. Look at the code below.
import React, { Component } from 'react' class App extends Component { constructor(props){ super(props); this.state={name:'',age:0,errorName:'',errorAge:''}; } handleSubmit=(e)=>{ if(this.state.errorAge==='' && this.state.errorName===''){ alert('Your name is: '+this.state.name +'\nYour age is: '+this.state.age); } else{ alert('Fill the form correctly!'); } } handleChange=(e)=>{ const name=e.target.name; const value=e.target.value; let error='',errors=''; if (name==="name" && value.trim()===''){ error=<strong style={{color:'red'}}>*{name} is required</strong>; } if(name==="age" && this.state.name.trim()===''){ error=<strong style={{color:'red'}}>*Name is required</strong>; } if (value<=0){ errors=<strong style={{color:'red'}}>*Age should be greater than 0</strong>; } this.setState({errorName:error,errorAge:errors}); this.setState({ [name]:value }); } render() { return ( <form onSubmit={this.handleSubmit}> <fieldset> <label for="name">Enter your name: </label> <input type="text" id="name" name="name" onChange={this.handleChange} /> {this.state.errorName} <br/><br/> <label for="age">Enter your age: </label> <input type="number" id="age" name="age" onChange={this.handleChange}/> {this.state.errorAge} <br/><br/> <button>Submit</button> </fieldset> </form> ) } } export default App
Notice the change in line no. 9. If the errorAge and errorName variables are empty, then only we print the submitted data. Otherwise, we alert the user to fill the form correctly.
The output would look like this:
On entering every field correctly, the output would be:
Conclusion:
We used the state to perform validation and print error messages respectively beside each input field. In addition, we did a final check before submitting the form. This was all about custom error messages and form validation in React Js. Keep learning.
Leave a Reply