How to Add Form Validation in React ?How to Save CheckBox,Radio Button,Input Field( Text&Date Type),drop-down Value in React?

radhe65gupta

Radheshyam Gupta

Posted on October 26, 2022

How to Add Form Validation in React ?How to Save CheckBox,Radio Button,Input Field( Text&Date Type),drop-down Value in React?

Go For Live Demo
If you've worked on any react applications React Hook played a big role to Control Html elements and its properties.

Hook Which played a big role for developing React Application are useState(),useEffect(),useRef() and More .

In This post i will work on useState() Hook to Save input Data.

Now we Come on Our Topic.

*How to Create a Form in React?
it is Design Part only.
*

<div className='FormValBody'>

                <div className='FormValInputLabel'><label>Name</label></div>
                <input type='text' name='Name' value={Name} onChange={(e) => { onInputChange(e,'inputTxt') } } /><br />
                <div className='FormErrorLabel'><label>{NameErrorMsg }</label></div>


                <div className='FormValInputLabel'><label>Mobile No</label></div>
                <input type='text' name='MobileNo' value={MobileNo} onChange={(e) => { onInputChange(e, 'inputTxt') }} /><br />
                <div className='FormErrorLabel'><label>{MobNoErrorMsg}</label></div>


                <div className='FormValInputLabel'><label>Email Address</label></div>
                <input type='text' name='EmailAddress' value={EmailAddress} onChange={(e) => { onInputChange(e, 'inputTxt') }} /><br />
                <div className='FormErrorLabel'><label>{EmailErrorMsg}</label></div>


                <div className='FormValInputLabel'><label>Gender</label></div>
                <label> Male </label><input type='radio' name='Gender' value='Male' onChange={(e) => { onInputChange(e, 'inputTxt') }} />
                <label> Female </label> <input name='Gender' type='radio' value='Female' onChange={(e) => { onInputChange(e, 'inputTxt') }} /><br />
                <div className='FormErrorLabel'><label>{GenderErrorMsg}</label></div>


                <div className='FormValInputLabel'><label>Date of Birth</label></div>
                <input type='date' name='DateOfBirth' value={DateOfBirth} onChange={(e) => { onInputChange(e, 'inputTxt') }} /><br />
                <div className='FormErrorLabel'><label>{DBOErrorMsg}</label></div>


                <div className='FormValInputLabel'><label>Language</label></div> 
                <label>Hindi</label><input type='checkBox' name='Language' value='Hindi' onChange={(e) => { onInputChange(e, 'inputChkBx') }} />
                <label>Marathi</label> <input name='Language' type='checkBox' value='Marathi' onChange={(e) => { onInputChange(e, 'inputChkBx') }} />
                <label>English</label> <input name='Language' type='checkBox' value='English' onChange={(e) => { onInputChange(e, 'inputChkBx') }} /><br />
                <div className='FormErrorLabel'><label>{LNGErrorMsg}</label></div>


                <div className='FormValInputLabel'><label>State</label></div>
                <select name='State' value={State} onChange={(e) => { onInputChange(e, 'inputTxt') }}>
                    <option value=''>---Select---</option>
                    {StateName.map((sName, index) => (
                        <option key={index + sName} value={sName}>{sName}</option>
                        ))}
                </select><br />
                <div className='FormErrorLabel'><label>{StateErrorMsg}</label></div>
                <button className='btnAdd' onClick={AddBtnFnt }>Add</button>
            </div>
Enter fullscreen mode Exit fullscreen mode

Now We create react Component for show out input data after our Form Validation has Completed.

import React from 'react';

const ShowMyTable = (props) => {

    const { data } = props;
    return (<>
        <div className='ShowTable'>
            <table>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Mobile No</th>
                        <th>Email Address</th>
                        <th>Gender</th>
                        <th>Date Of Birth</th>
                        <th>Language</th>
                        <th>State</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>{data.Name}</td>
                        <td>{data.MobileNo}</td>
                        <td>{data.EmailAddress}</td>
                        <td>{data.Gender}</td>
                        <td>{data.DateOfBirth}</td>
                        <td>{data.Language.toString()}</td>
                        <td>{data.State}</td>
                    </tr>

                </tbody>
            </table>
        </div>

    </>);
};
export default ShowMyTable ;
Enter fullscreen mode Exit fullscreen mode

*Finally We Create React Form and react Component For Show our Validated Data. Now We Create App.css file for Styling Our Form.
*

/*form Validation */

.FormValBody {
    float: left;
    padding: 10px 10px 10px 10px;
    background-color: azure;
}

    .FormValBody input {       
        padding: 5px 5px 5px 5px;
        border-color: gainsboro;
        outline-color: darkgrey;
        font-family: 'Times New Roman';
        font-size: 18px;
    }
.FormValBody input:active{
    outline-color:blue;
}

.FormValInputLabel{
    width:100px;
    float:left;
}
.FormErrorLabel{
    height:17px;
    padding-left:120px;
    font-family:'Comic Sans MS';
    font-size:12px;
    color:red;
}

.btnAdd {
    margin-top:25px;
    margin-bottom:15px;
    margin-left: 38%;
    border: none;
    padding: 10px 20px 10px 20px;
    background-color: ButtonFace;
}
.btnAdd:hover{
    cursor:pointer;
}
.ShowTable {
    float: left;
    padding: 10px 10px 10px 10px;
    background-color: azure;
}
    .ShowTable table, th, td {
        border: 1px solid black;
        border-collapse: collapse;
    }
Enter fullscreen mode Exit fullscreen mode

For Form Validation And Getting input Fields Value ,First We create Model related to our form.
Model For Form

const DetailsModel = {
    Name: '',
    MobileNo: '',
    EmailAddress: '',
    Gender: '',
    DateOfBirth: '',
    Language: [],
    State: ''
}
Enter fullscreen mode Exit fullscreen mode

Model For Validation Message

const ErrorModel = {
    NameErrorMsg: '',
    MobNoErrorMsg: '',
    EmailErrorMsg: '',
    GenderErrorMsg: '',
    DBOErrorMsg: '',
    LNGErrorMsg: '',
    StateErrorMsg: '',

}
Enter fullscreen mode Exit fullscreen mode

*Now we create Pattern For Mobile And Email Address Validate And Create Array of List For Our Drop-Down List. *


const StateName = ['Assam', 'Bihar', 'Chhattisgarh', 'Jharkhand', 'Karnataka', 'Maharashtra', 'Uttar Pradesh'];


const emailPattern = /[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$/;

const  MobNo = /^\d{10}$/;
Enter fullscreen mode Exit fullscreen mode

Next We Take Three State For Storing Input Data,Error Message and Showing Data Component

const [details, setDetails] = useState(DetailsModel);

    const [errorMsg, setErrorMsg] = useState(ErrorModel);

    const [showTable, setShowTable] = useState(<ShowMyTable data={details} />)
Enter fullscreen mode Exit fullscreen mode

*For Easily Access Value Of Our Object Model Key Value, we destructure our Model Object
*

/* Deestructuring Object*/

    const { Name, MobileNo, EmailAddress, Gender, DateOfBirth, Language, State } = details;

    const { NameErrorMsg, MobNoErrorMsg, EmailErrorMsg, GenderErrorMsg, DBOErrorMsg, LNGErrorMsg, StateErrorMsg } = errorMsg;
Enter fullscreen mode Exit fullscreen mode

Now We Create a Arrow Function For Update Out Input Field Value State.

const onInputChange = (e, inputType) => {
        const { name, value } = e.target;
        if (inputType === 'inputTxt') {

            setDetails((previous) => ({ ...previous, [name]: value }))

        }
        else if (inputType === 'inputChkBx') {

            if (e.target.checked) {

                setDetails((previous) => ({ ...previous, [name]: [...Language, value] }));
            }
            else {
                const filterData = Language.filter((lang) => { return lang !== value });

                setDetails((previous) => ({ ...previous, [name]: filterData }));
            }
        }

    }
Enter fullscreen mode Exit fullscreen mode

*After Storing This all Form Input fields data in state ,Now Time To validate Form. So We Create New Arrow Function for Validation. *

const ValidateData = () => {
        const validateObj = {};

        if (Name.length === 0) {

            validateObj.NameErrorMsg = 'Please Enter Name';
        }

        if (MobileNo.length === 0) {

            validateObj.MobNoErrorMsg = 'Please Enter Mobile No';
        }
        else if (!MobileNo.match(MobNo)) {

            validateObj.MobNoErrorMsg = 'Please Enter Valid Mobile No';
        }

        if (EmailAddress.length === 0) {

            validateObj.EmailErrorMsg = 'Please Enter Email Address';
        }
        else if (!EmailAddress.match(emailPattern)) {

            validateObj.EmailErrorMsg = 'Please Enter Valid Email Address';
        }

        if (Gender.length === 0) {

            validateObj.GenderErrorMsg = 'Please Select Gender';
        }
        if (DateOfBirth.length === 0) {

            validateObj.DBOErrorMsg = 'Please Enter Date of Birth';
        }

        if (DateOfBirth.length === 0) {

            validateObj.DBOErrorMsg = 'Please Enter Date of Birth';
        }

        if (Language.length === 0) {

            validateObj.LNGErrorMsg = 'Please Select Language';
        }
        if (State.length === 0) {

            validateObj.StateErrorMsg = 'Please Select State';
        }


        if (Object.keys(validateObj).length === 0) {
            setErrorMsg(() => (ErrorModel));
            return true;
        }
        else {

            setErrorMsg(() => ({ ...ErrorModel, ...validateObj }));
            return false;

        }


    }
Enter fullscreen mode Exit fullscreen mode

So Finally We Call This Validation Function On Add Button and And after Validation Of Data ,we Show Data in Component Which we Create .

const AddBtnFnt = () => {

        const validateRt = ValidateData();

        if (validateRt) {
            setShowTable(<ShowMyTable data={details} />);
        }


    }
Enter fullscreen mode Exit fullscreen mode

Now Finally We Validate Our Form. Final All Code are Below

import React, { useState } from 'react';
import './App.css';
import ShowMyTable from'./ShowMyTable';

const StateName = ['Assam', 'Bihar', 'Chhattisgarh', 'Jharkhand', 'Karnataka', 'Maharashtra', 'Uttar Pradesh'];

const DetailsModel = {
    Name: '',
    MobileNo: '',
    EmailAddress: '',
    Gender: '',
    DateOfBirth: '',
    Language: [],
    State: ''
}

const ErrorModel = {
    NameErrorMsg: '',
    MobNoErrorMsg: '',
    EmailErrorMsg: '',
    GenderErrorMsg: '',
    DBOErrorMsg: '',
    LNGErrorMsg: '',
    StateErrorMsg: '',

}

const emailPattern = /[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$/;
const  MobNo = /^\d{10}$/;



const FormValidationInReact = () => {

    const [details, setDetails] = useState(DetailsModel);

    const [errorMsg, setErrorMsg] = useState(ErrorModel);

    const [showTable, setShowTable] = useState(<ShowMyTable data={details} />)

    /* Deestructuring Object*/

    const { Name, MobileNo, EmailAddress, Gender, DateOfBirth, Language, State } = details;

    const { NameErrorMsg, MobNoErrorMsg, EmailErrorMsg, GenderErrorMsg, DBOErrorMsg, LNGErrorMsg, StateErrorMsg } = errorMsg;

    const onInputChange = (e, inputType) => {
        const { name, value } = e.target;
        if (inputType === 'inputTxt') {

            setDetails((previous) => ({ ...previous, [name]: value }))

        }
        else if (inputType === 'inputChkBx') {

            if (e.target.checked) {

                setDetails((previous) => ({ ...previous, [name]: [...Language, value] }));
            }
            else {
                const filterData = Language.filter((lang) => { return lang !== value });

                setDetails((previous) => ({ ...previous, [name]: filterData }));
            }
        }

    }


    const ValidateData = () => {
        const validateObj = {};

        if (Name.length === 0) {

            validateObj.NameErrorMsg = 'Please Enter Name';
        }

        if (MobileNo.length === 0) {

            validateObj.MobNoErrorMsg = 'Please Enter Mobile No';
        }
        else if (!MobileNo.match(MobNo)) {

            validateObj.MobNoErrorMsg = 'Please Enter Valid Mobile No';
        }

        if (EmailAddress.length === 0) {

            validateObj.EmailErrorMsg = 'Please Enter Email Address';
        }
        else if (!EmailAddress.match(emailPattern)) {

            validateObj.EmailErrorMsg = 'Please Enter Valid Email Address';
        }

        if (Gender.length === 0) {

            validateObj.GenderErrorMsg = 'Please Select Gender';
        }
        if (DateOfBirth.length === 0) {

            validateObj.DBOErrorMsg = 'Please Enter Date of Birth';
        }

        if (DateOfBirth.length === 0) {

            validateObj.DBOErrorMsg = 'Please Enter Date of Birth';
        }

        if (Language.length === 0) {

            validateObj.LNGErrorMsg = 'Please Select Language';
        }
        if (State.length === 0) {

            validateObj.StateErrorMsg = 'Please Select State';
        }


        if (Object.keys(validateObj).length === 0) {
            setErrorMsg(() => (ErrorModel));
            return true;
        }
        else {

            setErrorMsg(() => ({ ...ErrorModel, ...validateObj }));
            return false;

        }


    }


    const AddBtnFnt = () => {

        const validateRt = ValidateData();

        if (validateRt) {
            setShowTable(<ShowMyTable data={details} />);
        }


    }


    return (

        <>
            <div className='FormValBody'>

                <div className='FormValInputLabel'><label>Name</label></div>
                <input type='text' name='Name' value={Name} onChange={(e) => { onInputChange(e,'inputTxt') } } /><br />
                <div className='FormErrorLabel'><label>{NameErrorMsg }</label></div>


                <div className='FormValInputLabel'><label>Mobile No</label></div>
                <input type='text' name='MobileNo' value={MobileNo} onChange={(e) => { onInputChange(e, 'inputTxt') }} /><br />
                <div className='FormErrorLabel'><label>{MobNoErrorMsg}</label></div>


                <div className='FormValInputLabel'><label>Email Address</label></div>
                <input type='text' name='EmailAddress' value={EmailAddress} onChange={(e) => { onInputChange(e, 'inputTxt') }} /><br />
                <div className='FormErrorLabel'><label>{EmailErrorMsg}</label></div>


                <div className='FormValInputLabel'><label>Gender</label></div>
                <label> Male </label><input type='radio' name='Gender' value='Male' onChange={(e) => { onInputChange(e, 'inputTxt') }} />
                <label> Female </label> <input name='Gender' type='radio' value='Female' onChange={(e) => { onInputChange(e, 'inputTxt') }} /><br />
                <div className='FormErrorLabel'><label>{GenderErrorMsg}</label></div>


                <div className='FormValInputLabel'><label>Date of Birth</label></div>
                <input type='date' name='DateOfBirth' value={DateOfBirth} onChange={(e) => { onInputChange(e, 'inputTxt') }} /><br />
                <div className='FormErrorLabel'><label>{DBOErrorMsg}</label></div>


                <div className='FormValInputLabel'><label>Language</label></div> 
                <label>Hindi</label><input type='checkBox' name='Language' value='Hindi' onChange={(e) => { onInputChange(e, 'inputChkBx') }} />
                <label>Marathi</label> <input name='Language' type='checkBox' value='Marathi' onChange={(e) => { onInputChange(e, 'inputChkBx') }} />
                <label>English</label> <input name='Language' type='checkBox' value='English' onChange={(e) => { onInputChange(e, 'inputChkBx') }} /><br />
                <div className='FormErrorLabel'><label>{LNGErrorMsg}</label></div>


                <div className='FormValInputLabel'><label>State</label></div>
                <select name='State' value={State} onChange={(e) => { onInputChange(e, 'inputTxt') }}>
                    <option value=''>---Select---</option>
                    {StateName.map((sName, index) => (
                        <option key={index + sName} value={sName}>{sName}</option>
                        ))}
                </select><br />
                <div className='FormErrorLabel'><label>{StateErrorMsg}</label></div>
                <button className='btnAdd' onClick={AddBtnFnt }>Add</button>
            </div>

            {showTable }

        </>)
};


export default FormValidationInReact;

Enter fullscreen mode Exit fullscreen mode

Well done! Finally Validate Our For And Make A Awesome GUI !

Drop some love by liking or commenting ♥

Reference w3schools

Download Source Code from GitHub Repository

💖 💪 🙅 🚩
radhe65gupta
Radheshyam Gupta

Posted on October 26, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related