DEV Community

Radheshyam Gupta
Radheshyam Gupta

Posted on • Updated on

How Validate Form Input Data In React Or Any JavaScript Web Application ?

Go For Live Demo

In React Or Any JavaScript Web Application ,it is big challenging job to provide Valid Warning Message to User to provide Valid Data.

Today I just show to you with small program to fulfilled this challenging job in very easy way.

Now times to show Code;

First we Create A Method who Validate Out model .

//Note validateModel and validateModelData are javascript Object.
validateModel is our Model where we store our form data and 
validateModelData is model where we store out Validation message regarding our form Model with same key with Validation message .

export const ValidateMyModel = (validateModel, validateModelData) => {

    const validateFilterModel = {};
    const ReturnErrorList = [];

    for (const [key, value] of Object.entries(validateModelData)) {
        if (validateModel.hasOwnProperty(key)) {
            validateFilterModel[key] = validateModel[key];
        }
    }

    for (const [key, value] of Object.entries(validateFilterModel)) {
        if (!value)
        {
            ReturnErrorList.push(validateModelData[key]);
        }
    }
    return ReturnErrorList;


}
Enter fullscreen mode Exit fullscreen mode

*Now Time To implement this ValidateMyModel() on submit button.
I call a function submitData() on button click to save data.
*

const submitData = () => {

 const ErrorList = ValidateMyModel(modelData, RequiredFiledModel);

        if (ErrorList.length === 0) {

            if (TermsCondition) {
                alert("Data Successfully Saved")
            }
            else {
                alert("Please accept Terms and Condition");
            }
        }
        else {
            alert(ErrorList.toString());
        }


    }
Enter fullscreen mode Exit fullscreen mode

*Now I share With You all Code below
*

1) App.js File

import { useState } from 'react';
import './App.css';
import { countryList, DetailsModel, monthNames, RangeData, ValidateMyModel, RequiredFiledModel } from './Model/Model';

function App() {

    const [modelData, setModelData] = useState(DetailsModel);

    const { Name, Gender, Phone, Birthdate, BirthdateMonth, BirthdateYear,TermsCondition,Street,Nationality,City,Country } = modelData;

    const onInputChange = (event) => {

        const { name, value } = event.target;

        if (name === "TermsCondition") {
            if (event.target.checked) {

                setModelData((pre) => ({ ...pre, [name]: true }));
            }
            else {
                setModelData((pre) => ({ ...pre, [name]: false }));
            }

        }
        else {
            setModelData((pre) => ({ ...pre, [name]: value }));
        }


    }

    const submitData = () => {

        const ErrorList = ValidateMyModel(modelData, RequiredFiledModel);


        if (ErrorList.length === 0) {

            if (TermsCondition) {
                alert("Data Successfully Saved")
            }
            else {
                alert("Please accept Terms and Condition");
            }
        }
        else {
            alert(ErrorList.toString());
        }


    }

  return (
      <>

          <div className="main-block">
              <div className="formBody">
                      <h1>Model Validate Example</h1>                     
                      <fieldset>
                          <legend>
                              <h3>Personal Details</h3>
                          </legend>
                          <div className="personal-details">
                          <div>
                              <div><label>Name*</label><input type="text" name="Name" value={Name } onChange={(e) => { onInputChange(e)} } /></div>
                              <div><label>Phone*</label><input type="text" name="Phone" value={Phone} onChange={(e) => { onInputChange(e)} } /></div>
                              <div><label>Street</label><input type="text" name="Street" value={Street } onChange={(e) => { onInputChange(e)} } /></div>
                              <div><label>City*</label><input type="text" name="City" value={City } onChange={(e) => { onInputChange(e)} } /></div>
                                  <div>
                                  <label>Country*</label>
                                  <select name="Country" value={Country} onChange={(e) => { onInputChange(e) }} >
                                          <option value=""></option>
                                      {countryList.map((item, index) => (
                                          <option key={index + "Country"} value={item} >{item}</option>
                                      ))}
                                      </select>
                                  </div>

                              </div>
                              <div>
                                  <div>
                                      <label>Gender*</label>
                                      <div className="gender">
                                      <input type="radio" value="Male" id="male" name="Gender"  onChange={(e) => { onInputChange(e)} } />
                                          <label htmlFor="male" className="radio">Male</label>
                                      <input type="radio" value="Female" id="female" name="Gender"  onChange={(e) => { onInputChange(e)} } />
                                          <label htmlFor="female" className="radio">Female</label>
                                      </div>
                                  </div>
                                  <div className="birthdate">
                                      <label>Birthdate*</label>
                                  <div className="bdate-block">
                                      <select className="day" name="Birthdate" value={Birthdate} onChange={(e) => { onInputChange(e) }} >
                                          <option value=""></option>
                                          {
                                              RangeData(1,31)?.map((item, index) => (

                                                  <option key={index + "Date"} value={"0" + item}>{"0" + item}</option>

                                          ))                              
                                          }   
                                          </select>
                                      <select className="month" value={BirthdateMonth} name="BirthdateMonth" onChange={(e) => { onInputChange(e)} } >
                                          <option value=""></option>
                                          {monthNames.map((item, index) => (
                                              <option key={index + "month"} value={item} >{item}</option>
                                          ))}
                                          </select>
                                      <input type="text" name="BirthdateYear" value={BirthdateYear } onChange={(e) => { onInputChange(e)} } />
                                      </div>
                                  </div>
                                  <div>
                                      <label>Nationality*</label>
                                  <select name="Nationality" value={Nationality} onChange={(e) => { onInputChange(e)} } >
                                      <option value=""></option>
                                      {countryList.map((item, index) => (
                                          <option key={index + "Nationality"} value={item} >{item }</option>
                                          ))}
                                      </select>
                                  </div>                                  
                              </div>
                          </div>
                      </fieldset>
                      <fieldset>
                          <legend>
                              <h3>Terms and Condition</h3>
                          </legend>
                          <div className="terms-mailing">
                          <div className="checkbox">
                              <input type="checkbox" name="TermsCondition" checked={TermsCondition} onChange={(e) => { onInputChange(e) }} /><span>I accept the <a href="https://biharisoft.com/EduBox/">Biharisoft</a></span>
                              </div>                          
                              </div>
                  </fieldset>
                  <button type="submit" onClick={() => { submitData()} }>Submit</button>
              </div>
              </div>

      </>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

2) Mode.js

export const DetailsModel = {

    Name:"",
    Gender:"",
    Phone:"",
    Birthdate:"",
    Street: "",
    Nationality: "",
    City:"",
    Country: "",
    BirthdateMonth: "",
    BirthdateYear: "",
    TermsCondition: false

};


export const RequiredFiledModel = {

    Name: "Name Required",    
    Phone: "Phone Required",
    Birthdate: "Birth Date Required",
    Nationality: "Nationality Required",
    Country: "Country Required",
    BirthdateMonth: "Birth Month Required",
    BirthdateYear: "Birth Year Required"


};

export const countryList = [
    "Afghanistan",    
    "India",
    "Indonesia",
    "Iran (Islamic Republic of)",
    "Nepal",
    "United Kingdom of Great Britain and Northern Ireland (the)",
    "United States Minor Outlying Islands (the)",
    "United States of America (the)",
];

export const monthNames = ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"];

export const RangeData = (startVal, RangeVal) => {

    const List = [];
    for (let i = startVal; i <= RangeVal; i++) {
        List.push(i);
    }
    return List;
}

export const ValidateMyModel = (validateModel, validateModelData) => {
    console.log(validateModel);
    const validateFilterModel = {};
    const ReturnErrorList = [];

    for (const [key, value] of Object.entries(validateModelData)) {
        if (validateModel.hasOwnProperty(key)) {
            validateFilterModel[key] = validateModel[key];
        }
    }

    for (const [key, value] of Object.entries(validateFilterModel)) {
        if (!value)
        {
            ReturnErrorList.push(validateModelData[key]);
        }
    }
    return ReturnErrorList;


}

Enter fullscreen mode Exit fullscreen mode

3)App.css

html, body {
    min-height: 100%;
}

body, div, form, input, select, p {
    padding: 0;
    margin: 0;
    outline: none;
    font-family: Roboto, Arial, sans-serif;
    font-size: 14px;
    color: #666;
}

h1 {
    margin: 0;
    font-weight: 400;
}

h3 {
    margin: 12px 0;
    color: #8ebf42;
}

.main-block {
    display: flex;
    justify-content: center;
    align-items: center;
    background: #fff;
}

.formBody {
    width: 100%;
    padding: 20px;
}

fieldset {
    border: none;
    border-top: 1px solid #8ebf42;
}

.account-details, .personal-details {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
}

    .account-details > div, .personal-details > div > div {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
    }

    .account-details > div, .personal-details > div, input, label {
        width: 100%;
    }

label {
    padding: 0 5px;
    text-align: right;
    vertical-align: middle;
}

input {
    padding: 5px;
    vertical-align: middle;
}

.checkbox {
    margin-bottom: 10px;
}

select, .children, .gender, .bdate-block {
    width: calc(100% + 26px);
    padding: 5px 0;
}

select {
    background: transparent;
}

.gender input {
    width: auto;
}

.gender label {
    padding: 0 5px 0 0;
}

.bdate-block {
    display: flex;
    justify-content: space-between;
}

.birthdate select.day {
    width: 49px;
}

.birthdate select.month {
    width: calc(100% - 94px);
}

.birthdate input {
    width: 38px;
    vertical-align: unset;
}

.checkbox input, .children input {
    width: auto;
    margin: -2px 10px 0 0;
}

.checkbox a {
    color: #8ebf42;
}

    .checkbox a:hover {
        color: #82b534;
    }

button {
    width: 100%;
    padding: 10px 0;
    margin: 10px auto;
    border-radius: 5px;
    border: none;
    background: #8ebf42;
    font-size: 14px;
    font-weight: 600;
    color: #fff;
}

    button:hover {
        background: #82b534;
    }

@media (min-width: 568px) {
    .account-details > div, .personal-details > div {
        width: 50%;
    }

    label {
        width: 40%;
    }

    input {
        width: 60%;
    }

    select, .children, .gender, .bdate-block {
        width: calc(60% + 16px);
    }
}

Enter fullscreen mode Exit fullscreen mode

Well done! You now have Done Form Model Validation in React Web App!

Drop some love by liking or commenting ♥

Reference w3schools

Download Source Code from GitHub Repository

Top comments (0)