Forms And Basic Validations In React

Introduction

This is the sixth article of the basic react js series. In this article, we will create a basic form and add basic validations to the form inputs in react, and display the error messages on the page. 

In this series, we are learning about basic react js concepts. This article is about creating forms and validations in react.

Let's create one component with name registration and create a form with basic fields like name, country, comment, and term & condition. So we can cover the input box, drop-down list, checkbox, and text area. In this component, we have used state for input fields, and that field value is updated by onchange method. For validation just add one method validate where we check the values of input fields and if the field is blank then set the error message. Also, display that error message on the page.

Once the user clicks on submit button we use the preventDefault method that prevents the browser's default behavior from submitting a form. Now for displaying an error message we can use the if condition in react and display the message. 

Registration.js

import React ,{useState} from "react";

function Registration()
{
    const [name,setname]= useState("")
    const [country,setcountry]= useState("")
    const [comment,setcomment]= useState("")
    const [tandc,settandc]= useState(false)

    const [reqName,setreqName]= useState("")
    const [reqCountry,setreqCountry]= useState("")
    const [reqComment,setreqComment]= useState("")
    const [reqTandc,setreqTandc]= useState("")
      
    const submit =(e) => {
      e.preventDefault();
      resetErrorMessage();
      if(Validate())
        console.log(name,country,comment,tandc)
    }
    const Validate =()=>
    {
     if(name.trim() ==="") setreqName("required") 
     else if(country.trim() ==="") setreqCountry("required")   
     else if(comment.trim() ==="" ) setreqComment("required")  
     else if(tandc === false ) setreqTandc("required")  
     else return true      
    }
    const resetErrorMessage =()=>
    {
      setreqName(""); setreqCountry("") ;setreqComment("");setreqTandc("");
    }

    return (
        <div>
          <h1> Basic Form and Validation</h1>
          <form onSubmit={submit}>
           <table className="center">
           <tbody>
           <tr>
           <td>  Name:</td>
           <td> 
           <input type="text"   name="name" onChange={(e)=> setname(e.target.value)} />
           </td>
           <td>
           {reqName ==="required" && <span className="txt-red">Please enter name</span> }
           </td>
           </tr> 
           <tr>
           <td>  Country:</td>
           <td> 
           <select name="country"   onChange={(e)=> setcountry(e.target.value)}>
              <option value="">-----------Select------------</option>
              <option value="india">India</option>
               <option value="us">Us</option>
              </select>
              </td>
           <td>
              {reqCountry ==="required" && <span className="txt-red">Please select country</span>}
              </td>
           </tr>  
           <tr>
           <td>  Comment:</td>
           <td> 
           <textarea name="comment" onChange={(e)=> setcomment(e.target.value)}></textarea>
           </td>
           <td>
           {reqComment ==="required" && <span className="txt-red">Please enter comment</span>}
           </td>
           </tr>  
           <tr>
           <td> </td><td>
           <input type="checkbox"  name="tandc" onChange={(e)=> settandc(e.target.checked)} /> Term & condition
           </td>
           <td>
           {reqTandc ==="required" && <span className="txt-red">Please check trem & condition</span>}
           </td>
           </tr>  
           <tr>
            <td colSpan="3"> 
            <input type="submit"  value="Submit"   />
            </td>
           </tr>
           </tbody>
           </table>
           </form>
        </div>
      )  
}
export default Registration;

Now we need to import our new registration component into the app component.

App.js

import './App.css';
import Registration from './Registration';

function App() {
  return (
    <div className="App">    
     <Registration />  
    </div>
  );
}
export default App;

 Add some styling to the app.css for error validation text and text align center.

.txt-red{
  color: red;
}
.center{
  margin: 0px auto; 
}

Now let's run the application with npm start. it will open on the default browser as we can below output. We just use the console log to see the submitted values of the form.

Forms and Basic Validations in React

Summary

In this article, we have learned how to create a basic form in react and use basic validations in react. I hope you understand form creation and use basic validation in react. Thank you for reading this article.