Debug School

rakesh kumar
rakesh kumar

Posted on

List down different type of Validation in React js

When handling input changes in React.js, there are several ways to apply validation. Here are some common approaches with real examples:

Password Length field Validation
Numeric Value Validation Age
Email Validation Format
Date Validation:
URL Validation Format
facebook Validation Format
Phone Number Validation Format
phone number is valid for the selected country **
**File Type Validation

File Size Validation:
Checkbox Validation
Radio Button Validation
Checkbox Validation: with respect permission,status or active
Checkbox Validation: with respect dynamic data status retrive from database
Custom Validation Functions for email,
phone,
numeric,length
,date,
file extension,
age,
Credit Card Validation,
URL,
Check if Date is in the Future,
File Extension Validation,
Custom Pattern Validation,
Age Validation (Minimum Age) 18 years
Check if Date is within a Specific Range
Check if Date is a Weekend
Check if Date is a Leap Year
Check if Date is the Last Day of the Month
Check if Date is a Valid Birthday (age 18+)
Check if Date is on a Specific Day of the Week
Check if Date is a Business Day (Monday to Friday, excluding holidays
Comparing Field Values Validation for password and confirm password
Range Validation
Select Field Validation
Conditional Validation
Conditional switch Validation
button validation
Html heading validation
FormRow Validation
Email validation on keyup

Required Field Validation: Ensuring that a field is not left empty.

Length Validation: Checking the length of a field (e.g., minimum and maximum character limits).

Numeric Value Validation: Verifying that a field contains only numeric values.

Email Validation: Validating the format of an email address.

Password Validation: Enforcing password complexity rules (e.g., minimum length, uppercase, lowercase, special characters).

Date Validation: Validating the format and range of a date.

URL Validation: Verifying the format of a URL.

Phone Number Validation: Ensuring that a phone number follows a specific pattern.

Credit Card Validation: Validating credit card numbers using algorithms or regular expressions.

File Type Validation: Checking the file type based on its extension.

File Size Validation: Limiting the size of an uploaded file.

Checkbox Validation: Requiring the selection of at least one checkbox.

Radio Button Validation: Ensuring that one radio button option is selected.

Comparing Field Values: Validating that two fields have the same value (e.g., password and confirm password).

Custom Validation Functions: Implementing custom validation logic based on specific requirements.

Pattern Matching Validation: Checking if a field matches a specific pattern or regular expression.

Unique Value Validation: Verifying that a value is unique among existing records (e.g., username availability).

Range Validation: Ensuring that a numeric value falls within a specified range.

Select Field Validation: Requiring the selection of an option from a dropdown or select field.

Conditional Validation: Applying validation rules based on certain conditions or dependencies between fields.
Enter fullscreen mode Exit fullscreen mode

Required Field Validation

import React, { useState } from 'react';

function MyForm() {
  const [name, setName] = useState('');
  const [nameError, setNameError] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!name) {
      setNameError('Name is required');
      return;
    }

    // Perform form submission logic
    // ...
  };

  const handleChange = (e) => {
    setName(e.target.value);
    setNameError('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="name">Name:</label>
        <input type="text" id="name" value={name} onChange={handleChange} />
        {nameError && <span style={{ color: 'red' }}>{nameError}</span>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

In this example, we have a form with a single input field for the name. Here's how the Required Field Validation is implemented:

We initialize the name state variable to track the value of the name input field and nameError to track the error message.

In the handleSubmit function, we check if the name field is empty using !name condition. If it is empty, we set the nameError state to 'Name is required' and return early to prevent form submission.

In the handleChange function, we update the name state whenever the input value changes. We also reset the nameError state to an empty string to clear any previous error message.

Inside the JSX, we render the input field and the error message conditionally. If nameError is truthy, meaning there is an error message, we render a <span> element with the error message.
Enter fullscreen mode Exit fullscreen mode

Length field Validation

import React, { useState } from 'react';

function MyForm() {
  const [password, setPassword] = useState('');
  const [passwordError, setPasswordError] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();

    if (password.length < 6) {
      setPasswordError('Password must be at least 6 characters long');
      return;
    }

    // Perform form submission logic
    // ...
  };

  const handleChange = (e) => {
    setPassword(e.target.value);
    setPasswordError('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="password">Password:</label>
        <input type="password" id="password" value={password} onChange={handleChange} />
        {passwordError && <span style={{ color: 'red' }}>{passwordError}</span>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

In this example, we have a form with a password input field. Here's how the Length Field Validation is implemented:

We initialize the password state variable to track the value of the password input field and passwordError to track the error message.

In the handleSubmit function, we check if the length of the password is less than 6 characters using password.length < 6. If it is less, we set the passwordError state to 'Password must be at least 6 characters long' and return early to prevent form submission.

In the handleChange function, we update the password state whenever the input value changes. We also reset the passwordError state to an empty string to clear any previous error message.

Inside the JSX, we render the password input field and the error message conditionally. If passwordError is truthy, meaning there is an error message, we render a <span> element with the error message.
Enter fullscreen mode Exit fullscreen mode

Numeric Value Validation

import React, { useState } from 'react';

function MyForm() {
  const [age, setAge] = useState('');
  const [ageError, setAgeError] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!/^\d+$/.test(age)) {
      setAgeError('Age must be a numeric value');
      return;
    }

    // Perform form submission logic
    // ...
  };

  const handleChange = (e) => {
    setAge(e.target.value);
    setAgeError('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="age">Age:</label>
        <input type="text" id="age" value={age} onChange={handleChange} />
        {ageError && <span style={{ color: 'red' }}>{ageError}</span>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

**
Email Validation**

import React, { useState } from 'react';

function MyForm() {
  const [email, setEmail] = useState('');
  const [emailError, setEmailError] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!/\S+@\S+\.\S+/.test(email)) {
      setEmailError('Invalid email format');
      return;
    }

    // Perform form submission logic
    // ...
  };

  const handleChange = (e) => {
    setEmail(e.target.value);
    setEmailError('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="email">Email:</label>
        <input type="email" id="email" value={email} onChange={handleChange} />
        {emailError && <span style={{ color: 'red' }}>{emailError}</span>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

Password Validation

apply Password Validation in React.js, you can use state, regular expressions, and conditional rendering to display an error message when the password input does not meet the specified complexity rules. Here's an example:

import React, { useState } from 'react';

function MyForm() {
  const [password, setPassword] = useState('');
  const [passwordError, setPasswordError] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();

    if (password.length < 6) {
      setPasswordError('Password must be at least 6 characters long');
      return;
    }

    // Perform form submission logic
    // ...
  };

  const handleChange = (e) => {
    setPassword(e.target.value);
    setPasswordError('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="password">Password:</label>
        <input type="password" id="password" value={password} onChange={handleChange} />
        {passwordError && <span style={{ color: 'red' }}>{passwordError}</span>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;

Enter fullscreen mode Exit fullscreen mode

Date Validation:

import React, { useState } from 'react';

function MyForm() {
  const [date, setDate] = useState('');
  const [dateError, setDateError] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();

    const inputDate = new Date(date);

    if (isNaN(inputDate) || inputDate > new Date()) {
      setDateError('Invalid date');
      return;
    }

    // Perform form submission logic
    // ...
  };

  const handleChange = (e) => {
    setDate(e.target.value);
    setDateError('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="date">Date:</label>
        <input type="date" id="date" value={date} onChange={handleChange} />
        {dateError && <span style={{ color: 'red' }}>{dateError}</span>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

URL Validation on handlechange

import React, { useState } from 'react';

function MyForm() {
  const [url, setUrl] = useState('');
  const [urlError, setUrlError] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!/^https?:\/\/[\w.-]+\.\w{2,}(\/.*)?$/.test(url)) {
      setUrlError('Invalid URL format');
      return;
    }

    // Perform form submission logic
    // ...
  };

  const handleChange = (e) => {
    setUrl(e.target.value);
    setUrlError('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="url">URL:</label>
        <input type="text" id="url" value={url} onChange={handleChange} />
        {urlError && <span style={{ color: 'red' }}>{urlError}</span>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

facebook Validation

import React, { useState } from 'react';

function MyForm() {
  const [facebookUrl, setFacebookUrl] = useState('');
  const [facebookUrlError, setFacebookUrlError] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!/^https?:\/\/(www\.)?facebook\.com\/[A-Za-z0-9_.-]+\/?$/.test(facebookUrl)) {
      setFacebookUrlError('Invalid Facebook URL');
      return;
    }

    // Perform form submission logic
    // ...
  };

  const handleChange = (e) => {
    setFacebookUrl(e.target.value);
    setFacebookUrlError('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="facebookUrl">Facebook URL:</label>
        <input type="text" id="facebookUrl" value={facebookUrl} onChange={handleChange} />
        {facebookUrlError && <span style={{ color: 'red' }}>{facebookUrlError}</span>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

Phone Number Validation

import React, { useState } from 'react';

function MyForm() {
  const [phoneNumber, setPhoneNumber] = useState('');
  const [phoneNumberError, setPhoneNumberError] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!/^[0-9]{10}$/.test(phoneNumber)) {
      setPhoneNumberError('Invalid phone number');
      return;
    }

    // Perform form submission logic
    // ...
  };

  const handleChange = (e) => {
    setPhoneNumber(e.target.value);
    setPhoneNumberError('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="phoneNumber">Phone Number:</label>
        <input type="tel" id="phoneNumber" value={phoneNumber} onChange={handleChange} />
        {phoneNumberError && <span style={{ color: 'red' }}>{phoneNumberError}</span>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

**
country code validation**

**import React, { useState } from 'react';

function MyForm() {
  const [countryCode, setCountryCode] = useState('');

  const handleChange = (e) => {
    setCountryCode(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    // Perform form submission logic
    // ...
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="countryCode">Country Code:</label>
        <select id="countryCode" value={countryCode} onChange={handleChange}>
          <option value="">Select</option>
          <option value="+1">+1 (USA)</option>
          <option value="+44">+44 (UK)</option>
          <option value="+91">+91 (India)</option>
          {/* Add more country codes as needed */}
        </select>
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;**
Enter fullscreen mode Exit fullscreen mode

phone number is valid for the selected country validation

import React, { useState } from 'react';

function MyForm() {
  const [countryCode, setCountryCode] = useState('');
  const [phoneNumber, setPhoneNumber] = useState('');
  const [phoneNumberError, setPhoneNumberError] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!validatePhoneNumber()) {
      setPhoneNumberError('Invalid phone number');
      return;
    }

    // Perform form submission logic
    // ...
  };

  const handleChangeCountryCode = (e) => {
    setCountryCode(e.target.value);
  };

  const handleChangePhoneNumber = (e) => {
    setPhoneNumber(e.target.value);
    setPhoneNumberError('');
  };

  const validatePhoneNumber = () => {
    // Define regular expressions for different country phone number patterns
    const phonePatterns = {
      '+1': /^\+1\d{10}$/, // USA
      '+44': /^\+44\d{10}$/, // UK
      '+91': /^\+91\d{10}$/ // India
      // Add more country patterns as needed
    };

    const selectedPattern = phonePatterns[countryCode];

    return selectedPattern && selectedPattern.test(phoneNumber);
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="countryCode">Country Code:</label>
        <select id="countryCode" value={countryCode} onChange={handleChangeCountryCode}>
          <option value="">Select</option>
          <option value="+1">+1 (USA)</option>
          <option value="+44">+44 (UK)</option>
          <option value="+91">+91 (India)</option>
          {/* Add more country codes as needed */}
        </select>
      </div>
      <div>
        <label htmlFor="phoneNumber">Phone Number:</label>
        <input type="text" id="phoneNumber" value={phoneNumber} onChange={handleChangePhoneNumber} />
        {phoneNumberError && <span style={{ color: 'red' }}>{phoneNumberError}</span>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

phone number is valid for the selected all dynamic dropdown country

import React, { useState } from 'react';

function MyForm() {
  const [countryCode, setCountryCode] = useState('');
  const [phoneNumber, setPhoneNumber] = useState('');
  const [phoneNumberError, setPhoneNumberError] = useState('');

  const countries = [
    { code: '+1', name: 'USA' },
    { code: '+44', name: 'UK' },
    { code: '+91', name: 'India' },
    // Add more countries as needed
  ];

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!validatePhoneNumber()) {
      setPhoneNumberError('Invalid phone number');
      return;
    }

    // Perform form submission logic
    // ...
  };

  const handleChangeCountryCode = (e) => {
    setCountryCode(e.target.value);
  };

  const handleChangePhoneNumber = (e) => {
    setPhoneNumber(e.target.value);
    setPhoneNumberError('');
  };

  const validatePhoneNumber = () => {
    const selectedCountry = countries.find((country) => country.code === countryCode);

    if (!selectedCountry) return false;

    const phonePattern = new RegExp(`^${selectedCountry.code}\\d{10}$`);

    return phonePattern.test(phoneNumber);
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="countryCode">Country Code:</label>
        <select id="countryCode" value={countryCode} onChange={handleChangeCountryCode}>
          <option value="">Select</option>
          {countries.map((country) => (
            <option key={country.code} value={country.code}>
              {`${country.code} (${country.name})`}
            </option>
          ))}
        </select>
      </div>
      <div>
        <label htmlFor="phoneNumber">Phone Number:</label>
        <input type="text" id="phoneNumber" value={phoneNumber} onChange={handleChangePhoneNumber} />
        {phoneNumberError && <span style={{ color: 'red' }}>{phoneNumberError}</span>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

File Type Validation

import React, { useState } from 'react';

function MyForm() {
  const [file, setFile] = useState(null);
  const [fileError, setFileError] = useState('');

  const handleFileChange = (e) => {
    const selectedFile = e.target.files[0];

    if (selectedFile) {
      const fileType = selectedFile.type;

      if (fileType !== 'image/jpeg' && fileType !== 'image/png') {
        setFile(null);
        setFileError('Invalid file type. Only JPEG and PNG files are allowed.');
      } else {
        setFile(selectedFile);
        setFileError('');
      }
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!file) {
      setFileError('Please select a file.');
      return;
    }

    // Perform form submission logic
    // ...
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="file">Select File:</label>
        <input type="file" id="file" accept=".jpeg, .jpg, .png" onChange={handleFileChange} />
        {fileError && <span style={{ color: 'red' }}>{fileError}</span>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

File Size Validation:

import React, { useState } from 'react';

function MyForm() {
  const [file, setFile] = useState(null);
  const [fileError, setFileError] = useState('');

  const handleFileChange = (e) => {
    const selectedFile = e.target.files[0];

    if (selectedFile) {
      const fileSize = selectedFile.size / 1024; // Convert to KB

      if (fileSize > 5120) { // 5 MB limit
        setFile(null);
        setFileError('File size exceeds the allowed limit of 5MB.');
      } else {
        setFile(selectedFile);
        setFileError('');
      }
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!file) {
      setFileError('Please select a file.');
      return;
    }

    // Perform form submission logic
    // ...
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="file">Select File:</label>
        <input type="file" id="file" onChange={handleFileChange} />
        {fileError && <span style={{ color: 'red' }}>{fileError}</span>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

Checkbox Validation

import React, { useState } from 'react';

function MyForm() {
  const [isChecked, setIsChecked] = useState(false);
  const [checkboxError, setCheckboxError] = useState('');

  const handleCheckboxChange = () => {
    setIsChecked(!isChecked);
    setCheckboxError('');
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!isChecked) {
      setCheckboxError('Please check the checkbox.');
      return;
    }

    // Perform form submission logic
    // ...
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>
          <input type="checkbox" checked={isChecked} onChange={handleCheckboxChange} />
          I agree to the terms and conditions
        </label>
        {checkboxError && <span style={{ color: 'red' }}>{checkboxError}</span>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

Radio Button Validation

import React, { useState } from 'react';

function MyForm() {
  const [selectedOption, setSelectedOption] = useState('');
  const [radioError, setRadioError] = useState('');

  const handleOptionChange = (e) => {
    setSelectedOption(e.target.value);
    setRadioError('');
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    if (selectedOption === '') {
      setRadioError('Please select an option.');
      return;
    }

    // Perform form submission logic
    // ...
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>
          <input
            type="radio"
            value="option1"
            checked={selectedOption === 'option1'}
            onChange={handleOptionChange}
          />
          Option 1
        </label>
        <label>
          <input
            type="radio"
            value="option2"
            checked={selectedOption === 'option2'}
            onChange={handleOptionChange}
          />
          Option 2
        </label>
        {radioError && <span style={{ color: 'red' }}>{radioError}</span>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

Checkbox Validation: with respect permission,status or active

import React, { useState } from 'react';

function MyForm() {
  const [permissions, setPermissions] = useState({
    read: false,
    write: false,
    delete: false,
  });
  const [permissionError, setPermissionError] = useState('');

  const handleCheckboxChange = (e) => {
    const { name, checked } = e.target;

    setPermissions((prevState) => ({
      ...prevState,
      [name]: checked,
    }));

    setPermissionError('');
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!permissions.read || !permissions.write || !permissions.delete) {
      setPermissionError('Please select all required permissions.');
      return;
    }

    // Perform form submission logic
    // ...
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>
          <input
            type="checkbox"
            name="read"
            checked={permissions.read}
            onChange={handleCheckboxChange}
          />
          Read
        </label>
        <label>
          <input
            type="checkbox"
            name="write"
            checked={permissions.write}
            onChange={handleCheckboxChange}
          />
          Write
        </label>
        <label>
          <input
            type="checkbox"
            name="delete"
            checked={permissions.delete}
            onChange={handleCheckboxChange}
          />
          Delete
        </label>
        {permissionError && <span style={{ color: 'red' }}>{permissionError}</span>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

Checkbox Validation: with respect dynamic data status retrive from database

import React, { useState, useEffect } from 'react';

function MyForm() {
  const [data, setData] = useState([]);
  const [checkedItems, setCheckedItems] = useState({});
  const [checkboxError, setCheckboxError] = useState('');

  useEffect(() => {
    // Simulating fetching data from the database
    const fetchData = async () => {
      try {
        // Fetch data from the API or database
        const response = await fetch('/api/data');
        const data = await response.json();

        setData(data);

        // Initialize checkedItems state based on the data status
        const initialCheckedItems = {};
        data.forEach((item) => {
          if (item.status === 'no') {
            initialCheckedItems[item.id] = false;
          }
        });
        setCheckedItems(initialCheckedItems);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, []);

  const handleCheckboxChange = (e) => {
    const { name, checked } = e.target;

    setCheckedItems((prevState) => ({
      ...prevState,
      [name]: checked,
    }));

    setCheckboxError('');
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    const uncheckedItems = Object.keys(checkedItems).filter((item) => !checkedItems[item]);

    if (uncheckedItems.length > 0) {
      setCheckboxError('Please check all items with status "no".');
      return;
    }

    // Perform form submission logic
    // ...
  };

  return (
    <form onSubmit={handleSubmit}>
      {data.map((item) => (
        <div key={item.id}>
          <label>
            <input
              type="checkbox"
              name={item.id}
              checked={checkedItems[item.id] || false}
              onChange={handleCheckboxChange}
              disabled={item.status === 'no' ? false : true}
            />
            {item.name}
          </label>
        </div>
      ))}
      {checkboxError && <span style={{ color: 'red' }}>{checkboxError}</span>}
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

In this example, we fetch data from the database and render checkboxes based on the retrieved data. Here's how the Checkbox Validation is implemented based on the status being "no":

We initialize the data state variable to store the fetched data, checkedItems state to track the checked status of each item, and checkboxError state to manage the error message.

We use the useEffect hook to fetch the data from the API or database when the component mounts. Inside the effect, we simulate the fetching process and store the retrieved data in the data state. We also initialize the checkedItems state based on the data's status. Only items with a status of "no" will be enabled for checking.

In the handleCheckboxChange function, we update the checkedItems state based on the checkbox's name (item ID) and checked properties. We clear any previous error message by setting checkboxError to an empty string.

In the handleSubmit function, we check if there are any unchecked items. We filter out the items where checkedItems[item] is false and store them in the uncheckedItems array. If there are unchecked items, we set the checkboxError state to 'Please check all items with status "no"' and return early to prevent form submission.

Inside the JSX, we map over the data array to render the checkboxes dynamically. Each checkbox's name attribute is set to the item's ID, and the checked attribute is determined based on the checkedItems state. The onChange event is connected to the handleCheckboxChange function. Additionally, the checkboxes are disabled for items with a status other than "no". The error message is rendered conditionally if checkboxError is truthy.
Enter fullscreen mode Exit fullscreen mode

By implementing this code, the form will display the 'Please check all items with status "no"' error message if any of the checkboxes with a status of "no" are left unchecked. The error message will disappear once all checkboxes with a status of "no" are checked.
Custom Validation Functions

import React, { useState } from 'react';

function MyForm() {
  const [inputValue, setInputValue] = useState('');
  const [inputError, setInputError] = useState('');

  const handleInputChange = (e) => {
    setInputValue(e.target.value);
    setInputError('');
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!validateInput(inputValue)) {
      setInputError('Invalid input. Please enter a valid value.');
      return;
    }

    // Perform form submission logic
    // ...
  };

  const validateInput = (value) => {
    // Add your custom validation logic here
    // Return true if the value is valid, false otherwise

    // Example: Check if the value is a valid email address
    const emailPattern = /\S+@\S+\.\S+/;
    return emailPattern.test(value);
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="input">Input:</label>
        <input type="text" id="input" value={inputValue} onChange={handleInputChange} />
        {inputError && <span style={{ color: 'red' }}>{inputError}</span>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode
**Email Validation**:
Enter fullscreen mode Exit fullscreen mode
const validateEmail = (value) => {
  const emailPattern = /\S+@\S+\.\S+/;
  return emailPattern.test(value);
};
Enter fullscreen mode Exit fullscreen mode
**Password Validation (Minimum Length)**:
Enter fullscreen mode Exit fullscreen mode
const validatePassword = (value) => {
  return value.length >= 8;
};
Enter fullscreen mode Exit fullscreen mode
**Phone Number Validation**:
Enter fullscreen mode Exit fullscreen mode
const validatePhoneNumber = (value) => {
  const phonePattern = /^\d{10}$/;
  return phonePattern.test(value);
};
Enter fullscreen mode Exit fullscreen mode
**Numeric Value Validation**:
Enter fullscreen mode Exit fullscreen mode
const validateNumericValue = (value) => {
  return !isNaN(parseFloat(value)) && isFinite(value);
};
Enter fullscreen mode Exit fullscreen mode
**URL Validation**:
Enter fullscreen mode Exit fullscreen mode
const validateURL = (value) => {
  const urlPattern = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i;
  return urlPattern.test(value);
};
Enter fullscreen mode Exit fullscreen mode

Date Validation (Check if Date is in the Future):

const validateFutureDate = (value) => {
  const inputDate = new Date(value);
  const currentDate = new Date();
  return inputDate > currentDate;
};
Enter fullscreen mode Exit fullscreen mode
**File Extension Validation**:
Enter fullscreen mode Exit fullscreen mode
const validateFileExtension = (value) => {
  const allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
  const fileExtension = value.split('.').pop().toLowerCase();
  return allowedExtensions.includes(fileExtension);
};
Enter fullscreen mode Exit fullscreen mode
**Custom Pattern Validation**:
Enter fullscreen mode Exit fullscreen mode
const validatePattern = (value) => {
  const pattern = /^[A-Za-z]+$/;
  return pattern.test(value);
};
Enter fullscreen mode Exit fullscreen mode
**Age Validation (Minimum Age)**:
Enter fullscreen mode Exit fullscreen mode
const validateAge = (value) => {
  const minimumAge = 18;
  const birthDate = new Date(value);
  const currentDate = new Date();
  const age = currentDate.getFullYear() - birthDate.getFullYear();
  return age >= minimumAge;
};


Enter fullscreen mode Exit fullscreen mode

Credit Card Validation (Luhn Algorithm):

const validateCreditCard = (value) => {
  const sanitizedValue = value.replace(/\D/g, '');
  let sum = 0;
  let shouldDouble = false;

  for (let i = sanitizedValue.length - 1; i >= 0; i--) {
    let digit = parseInt(sanitizedValue.charAt(i));

    if (shouldDouble) {
      digit *= 2;
      if (digit > 9) {
        digit -= 9;
      }
    }

    sum += digit;
    shouldDouble = !shouldDouble;
  }

  return sum % 10 === 0;
};

Enter fullscreen mode Exit fullscreen mode

These are just a few examples of custom validation functions you can create in React.js. You can modify and expand upon these functions based on your specific validation requirements.

**Check if Date is in the Future**:
Enter fullscreen mode Exit fullscreen mode
const validateFutureDate = (value) => {
  const inputDate = new Date(value);
  const currentDate = new Date();
  return inputDate > currentDate;
};
Enter fullscreen mode Exit fullscreen mode
**Check if Date is in the Past**:
Enter fullscreen mode Exit fullscreen mode
const validatePastDate = (value) => {
  const inputDate = new Date(value);
  const currentDate = new Date();
  return inputDate < currentDate;
};
Enter fullscreen mode Exit fullscreen mode
**Check if Date is within a Specific Range**:
Enter fullscreen mode Exit fullscreen mode
const validateDateRange = (value, startDate, endDate) => {
  const inputDate = new Date(value);
  const start = new Date(startDate);
  const end = new Date(endDate);
  return inputDate >= start && inputDate <= end;
};
Enter fullscreen mode Exit fullscreen mode
**Check if Date is a Weekend**:
Enter fullscreen mode Exit fullscreen mode
const validateWeekendDate = (value) => {
  const inputDate = new Date(value);
  return inputDate.getDay() === 0 || inputDate.getDay() === 6;
};
Enter fullscreen mode Exit fullscreen mode
**Check if Date is a Weekday**:
Enter fullscreen mode Exit fullscreen mode
const validateWeekdayDate = (value) => {
  const inputDate = new Date(value);
  return inputDate.getDay() >= 1 && inputDate.getDay() <= 5;
};
Enter fullscreen mode Exit fullscreen mode
**Check if Date is a Leap Year**:
Enter fullscreen mode Exit fullscreen mode
const validateLeapYear = (value) => {
  const inputYear = new Date(value).getFullYear();
  return (inputYear % 4 === 0 && inputYear % 100 !== 0) || inputYear % 400 === 0;
};
Enter fullscreen mode Exit fullscreen mode
**Check if Date is the Last Day of the Month:**
Enter fullscreen mode Exit fullscreen mode
const validateLastDayOfMonth = (value) => {
  const inputDate = new Date(value);
  const nextDay = new Date(inputDate);
  nextDay.setDate(nextDay.getDate() + 1);
  return nextDay.getMonth() !== inputDate.getMonth();
};
Enter fullscreen mode Exit fullscreen mode
**Check if Date is a Valid Birthday (age 18+)**:
Enter fullscreen mode Exit fullscreen mode
const validateBirthday = (value) => {
  const inputDate = new Date(value);
  const currentDate = new Date();
  const diffInYears = currentDate.getFullYear() - inputDate.getFullYear();
  if (diffInYears < 18) {
    return false;
  } else if (diffInYears === 18) {
    return currentDate.getMonth() > inputDate.getMonth() ||
      (currentDate.getMonth() === inputDate.getMonth() && currentDate.getDate() >= inputDate.getDate());
  }
  return true;
};
Enter fullscreen mode Exit fullscreen mode
**Check if Date is on a Specific Day of the Week:**
Enter fullscreen mode Exit fullscreen mode
const validateSpecificDayOfWeek = (value, dayOfWeek) => {
  const inputDate = new Date(value);
  return inputDate.getDay() === dayOfWeek;
};
Enter fullscreen mode Exit fullscreen mode
**Check if Date is a Business Day (Monday to Friday, excluding holidays):**
Enter fullscreen mode Exit fullscreen mode
const validateBusinessDay = (value, holidays = []) => {
  const inputDate = new Date(value);
  const dayOfWeek = inputDate.getDay();
  const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;
  const isHoliday = holidays.some((holiday) => new Date(holiday).toDateString() === inputDate.toDateString());
  return !isWeekend && !isHoliday;
};

Enter fullscreen mode Exit fullscreen mode

Credit Card Validation

import React, { useState } from 'react';
import CreditCardValidator from 'credit-card-validator'; // Import the credit card validation library

function MyForm() {
  const [country, setCountry] = useState('');
  const [creditCardNumber, setCreditCardNumber] = useState('');
  const [creditCardError, setCreditCardError] = useState('');

  const handleCountryChange = (e) => {
    setCountry(e.target.value);
    setCreditCardNumber('');
    setCreditCardError('');
  };

  const handleCreditCardChange = (e) => {
    setCreditCardNumber(e.target.value);
    setCreditCardError('');
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    if (country === 'US' && !CreditCardValidator.number(creditCardNumber).isValid) {
      setCreditCardError('Invalid credit card number');
      return;
    }

    // Perform form submission logic
    // ...
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="country">Country:</label>
        <select id="country" value={country} onChange={handleCountryChange}>
          <option value="">Select Country</option>
          <option value="US">United States</option>
          <option value="CA">Canada</option>
          {/* Add more country options */}
        </select>
      </div>
      {country === 'US' && (
        <div>
          <label htmlFor="creditCardNumber">Credit Card Number:</label>
          <input
            type="text"
            id="creditCardNumber"
            value={creditCardNumber}
            onChange={handleCreditCardChange}
          />
          {creditCardError && <span style={{ color: 'red' }}>{creditCardError}</span>}
        </div>
      )}
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode
import React, { useState } from 'react';

function MyForm() {
  const [creditCardNumber, setCreditCardNumber] = useState('');
  const [creditCardError, setCreditCardError] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!isValidCreditCardNumber(creditCardNumber)) {
      setCreditCardError('Invalid credit card number');
      return;
    }

    // Perform form submission logic
    // ...
  };

  const handleChange = (e) => {
    setCreditCardNumber(e.target.value);
    setCreditCardError('');
  };

  const isValidCreditCardNumber = (number) => {
    const regex = /^[0-9]{13,19}$/; // Regular expression for credit card number format
    return regex.test(number);
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="creditCardNumber">Credit Card Number:</label>
        <input
          type="text"
          id="creditCardNumber"
          value={creditCardNumber}
          onChange={handleChange}
        />
        {creditCardError && <span style={{ color: 'red' }}>{creditCardError}</span>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

**
Comparing Field Values Validation**

import React, { useState } from 'react';

function MyForm() {
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [passwordError, setPasswordError] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();

    if (password !== confirmPassword) {
      setPasswordError('Passwords do not match');
      return;
    }

    // Perform form submission logic
    // ...
  };

  const handlePasswordChange = (e) => {
    setPassword(e.target.value);
    setPasswordError('');
  };

  const handleConfirmPasswordChange = (e) => {
    setConfirmPassword(e.target.value);
    setPasswordError('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="password">Password:</label>
        <input type="password" id="password" value={password} onChange={handlePasswordChange} />
      </div>
      <div>
        <label htmlFor="confirmPassword">Confirm Password:</label>
        <input
          type="password"
          id="confirmPassword"
          value={confirmPassword}
          onChange={handleConfirmPasswordChange}
        />
        {passwordError && <span style={{ color: 'red' }}>{passwordError}</span>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

Range Validation

import React, { useState } from 'react';

function MyForm() {
  const [inputValue, setInputValue] = useState('');
  const [inputError, setInputError] = useState('');

  const handleInputChange = (e) => {
    setInputValue(e.target.value);
    setInputError('');
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!validateRange(inputValue, 10, 50)) {
      setInputError('Value must be between 10 and 50.');
      return;
    }

    // Perform form submission logic
    // ...
  };

  const validateRange = (value, min, max) => {
    return value >= min && value <= max;
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="input">Input:</label>
        <input type="number" id="input" value={inputValue} onChange={handleInputChange} />
        {inputError && <span style={{ color: 'red' }}>{inputError}</span>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

Select Field Validation

import React, { useState } from 'react';

function MyForm() {
  const [selectedOption, setSelectedOption] = useState('');
  const [selectError, setSelectError] = useState('');

  const handleSelectChange = (e) => {
    setSelectedOption(e.target.value);
    setSelectError('');
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    if (selectedOption === '') {
      setSelectError('Please select an option.');
      return;
    }

    // Perform form submission logic
    // ...
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="select">Select Option:</label>
        <select id="select" value={selectedOption} onChange={handleSelectChange}>
          <option value="">-- Select an option --</option>
          <option value="option1">Option 1</option>
          <option value="option2">Option 2</option>
          <option value="option3">Option 3</option>
        </select>
        {selectError && <span style={{ color: 'red' }}>{selectError}</span>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

Conditional Validation

import React, { useState } from 'react';

function MyForm() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [passwordError, setPasswordError] = useState('');

  const handleEmailChange = (e) => {
    setEmail(e.target.value);
  };

  const handlePasswordChange = (e) => {
    setPassword(e.target.value);
  };

  const handleConfirmPasswordChange = (e) => {
    setConfirmPassword(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    if (password !== confirmPassword) {
      setPasswordError('Passwords do not match.');
      return;
    }

    // Perform form submission logic
    // ...
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="email">Email:</label>
        <input type="email" id="email" value={email} onChange={handleEmailChange} />
      </div>
      <div>
        <label htmlFor="password">Password:</label>
        <input type="password" id="password" value={password} onChange={handlePasswordChange} />
      </div>
      <div>
        <label htmlFor="confirmPassword">Confirm Password:</label>
        <input
          type="password"
          id="confirmPassword"
          value={confirmPassword}
          onChange={handleConfirmPasswordChange}
        />
        {passwordError && <span style={{ color: 'red' }}>{passwordError}</span>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

Conditional switch Validation

import React, { useState } from 'react';

function MyForm() {
  const [option, setOption] = useState('');
  const [inputValue, setInputValue] = useState('');
  const [error, setError] = useState('');

  const handleOptionChange = (e) => {
    setOption(e.target.value);
    setInputValue('');
    setError('');
  };

  const handleInputChange = (e) => {
    setInputValue(e.target.value);
    setError('');
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    switch (option) {
      case 'option1':
        if (inputValue.trim() === '') {
          setError('Input is required for Option 1.');
          return;
        }
        // Additional validation logic for Option 1
        break;
      case 'option2':
        if (inputValue.length !== 10) {
          setError('Input must be 10 characters long for Option 2.');
          return;
        }
        // Additional validation logic for Option 2
        break;
      case 'option3':
        // Validation logic for Option 3
        break;
      default:
        setError('Please select an option.');
        return;
    }

    // Perform form submission logic
    // ...
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>Select Option:</label>
        <select value={option} onChange={handleOptionChange}>
          <option value="">-- Select an option --</option>
          <option value="option1">Option 1</option>
          <option value="option2">Option 2</option>
          <option value="option3">Option 3</option>
        </select>
      </div>
      {option && (
        <div>
          <label>Input:</label>
          <input type="text" value={inputValue} onChange={handleInputChange} />
        </div>
      )}
      {error && <span style={{ color: 'red' }}>{error}</span>}
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

In this example, we have a form with a select field and an input field. Here's how the Conditional Switch Validation is implemented:

We initialize state variables for option, inputValue, and error.

We handle the changes in the select field and input field by updating the respective state variables. When the option is changed, we also reset the input value and error message.

In the handleSubmit function, we use a switch statement to perform different validations based on the selected option. Each case represents a different option and has its own specific validation logic. If a validation fails, we set the error state to the corresponding error message and return early to prevent form submission.

Inside the JSX, we render the select field with its options. The value and onChange attributes of the select field are connected to the option state. We conditionally render the input field based on whether an option is selected. Additionally, we conditionally render the error message if error is truthy.
Enter fullscreen mode Exit fullscreen mode

Apply Validation on handlechange

**Inline Validation**:
In this approach, validation logic is directly applied within the handleChange function. You can use conditional statements or regular expressions to validate the input value. Here's an example:
Enter fullscreen mode Exit fullscreen mode
// State initialization
const [email, setEmail] = useState('');
const [emailError, setEmailError] = useState('');

// Handle input change
const handleChange = (e) => {
  const value = e.target.value;
  setEmail(value);

  // Validate email
  if (!value) {
    setEmailError('Email is required');
  } else if (!/\S+@\S+\.\S+/.test(value)) {
    setEmailError('Invalid email format');
  } else {
    setEmailError('');
  }
};

<input type="email" value={email} onChange={handleChange} />
{emailError && <span className="error">{emailError}</span>}
Enter fullscreen mode Exit fullscreen mode

In this example, the handleChange function validates the email input. If the value is empty, it sets the emailError state to 'Email is required'. If the value does not match the email format, it sets emailError to 'Invalid email format'. Otherwise, it clears the error message.

Separate Validation Function:
Another approach is to define a separate function to handle validation logic and call it within the handleChange function. Here's an example:

// State initialization
const [password, setPassword] = useState('');
const [passwordError, setPasswordError] = useState('');

// Validation function
const validatePassword = (value) => {
  if (!value) {
    return 'Password is required';
  } else if (value.length < 6) {
    return 'Password must be at least 6 characters long';
  }
  return '';
};

// Handle input change
const handleChange = (e) => {
  const value = e.target.value;
  setPassword(value);
  setPasswordError(validatePassword(value));
};

<input type="password" value={password} onChange={handleChange} />
{passwordError && <span className="error">{passwordError}</span>}

Enter fullscreen mode Exit fullscreen mode

In this example, the validatePassword function handles the password validation logic. It returns an error message based on the provided password value. The handleChange function calls validatePassword and sets the passwordError state accordingly.

External Validation Libraries:
React also provides external libraries specifically designed for form validation. These libraries offer more advanced features and flexibility. Here's an example using the popular Formik library:


    import { useFormik } from 'formik';

    // Formik validation schema
    const validationSchema = Yup.object({
      name: Yup.string().required('Name is required'),
      age: Yup.number().required('Age is required').min(18, 'Must be at least 18 years old'),
    });

    // Formik form configuration
    const formik = useFormik({
      initialValues: {
        name: '',
        age: '',
      },
      validationSchema,
      onSubmit: (values) => {
        // Handle form submission
      },
    });

    // Render JSX
    <form onSubmit={formik.handleSubmit}>
      <input type="text" name="name" value={formik.values.name} onChange={formik.handleChange} />
      {formik.errors.name && formik.touched.name && <span className="error">{formik.errors.name}</span>}
      <input type="number" name="age" value={formik.values.age} onChange={formik.handleChange} />
      {formik.errors.age && formik.touched.age && <span className="error">{formik.errors.age}</span>}
      <button type="submit">Submit</button>
    </form>
Enter fullscreen mode Exit fullscreen mode
In this example, the Formik library is used for form handling and validation. The validationSchema defines the validation rules using the Yup validation library. Formik automatically handles the validation logic based on the schema. Error messages are displayed when there are validation errors.
Enter fullscreen mode Exit fullscreen mode

These are just a few examples of how you can apply validation on handleChange in React.js. The approach you choose depends on the complexity of your validation requirements and the libraries or tools you prefer to use.

Apply Validation on handlesubmit

here are several ways to apply validation. Here are some common approaches with real examples:

**Inline Validation**:
In this approach, validation logic is directly applied within the handleSubmit function. You can use conditional statements or regular expressions to validate the form inputs. Here's an example:
Enter fullscreen mode Exit fullscreen mode
// State initialization
const [email, setEmail] = useState('');
const [emailError, setEmailError] = useState('');

// Handle form submission
const handleSubmit = (e) => {
  e.preventDefault();

  // Validate email
  if (!email) {
    setEmailError('Email is required');
    return;
  } else if (!/\S+@\S+\.\S+/.test(email)) {
    setEmailError('Invalid email format');
    return;
  }

  // Form submission logic
  // ...
};

// Render JSX
<form onSubmit={handleSubmit}>
  <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
  {emailError && <span className="error">{emailError}</span>}
  <button type="submit">Submit</button>
</form>
Enter fullscreen mode Exit fullscreen mode

In this example, the handleSubmit function validates the email input. If the value is empty, it sets the emailError state to 'Email is required'. If the value does not match the email format, it sets emailError to 'Invalid email format'. If the validation passes, the form submission logic can be executed.

External Validation Libraries:
React provides external libraries specifically designed for form validation. These libraries offer more advanced features and flexibility. Here's an example using the popular Formik library:

import { Formik, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';

// Formik validation schema
const validationSchema = Yup.object({
  email: Yup.string().email('Invalid email format').required('Email is required'),
  password: Yup.string().min(6, 'Password must be at least 6 characters').required('Password is required'),
});

// Handle form submission
const handleSubmit = (values) => {
  // Form submission logic
  // ...
};

// Render JSX
<Formik
  initialValues={{ email: '', password: '' }}
  validationSchema={validationSchema}
  onSubmit={handleSubmit}
>
  <form>
    <Field type="email" name="email" />
    <ErrorMessage name="email" component="div" className="error" />
    <Field type="password" name="password" />
    <ErrorMessage name="password" component="div" className="error" />
    <button type="submit">Submit</button>
  </form>
</Formik>
Enter fullscreen mode Exit fullscreen mode

In this example, the Formik library is used for form handling and validation. The validationSchema defines the validation rules using the Yup validation library. Formik automatically handles the validation logic based on the schema. Error messages are displayed using the ErrorMessage component.

Custom Validation Functions

If you prefer a more customized approach, you can define your own validation functions and call them within the handleSubmit function. Here's an example:

// State initialization
const [email, setEmail] = useState('');
const [emailError, setEmailError] = useState('');

// Email validation function
const validateEmail = () => {
  if (!email) {
    setEmailError('Email is required');
    return false;
  } else if (!/\S+@\S+\.\S+/.test(email)) {
    setEmailError('Invalid email format');
    return false;
  }
  return true;
};

// Handle form submission
const handleSubmit = (e) => {
  e.preventDefault();

  // Validate email
  if (!validateEmail()) {
    return;
  }

  // Form submission logic
  // ...
};

// Render JSX
<form onSubmit={handleSubmit}>
  <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
  {emailError && <span className="error">{emailError}</span>}
  <button type="submit">Submit</button>
</form>
Enter fullscreen mode Exit fullscreen mode

In this example, the validateEmail function handles the email validation logic. It checks if the email is empty or does not match the email format and sets the emailError state accordingly. The handleSubmit function calls validateEmail and returns early if the validation fails.

conditional field validation


const QuestionModal = () => {
  // const { isClientEditing, closeClientModal } = useAppContext()
  const {

    feedback,
    // closeClientModal,
    isModal,

  } = useAppContext()
  const [values, setValues] = useState({initialState})
Enter fullscreen mode Exit fullscreen mode
  if (!feedback || feedback.length === 0) {
    return <p><b>You have already submitted Feedback.</b></p>;
  }

Enter fullscreen mode Exit fullscreen mode

Html heading validation

<div className="button-container">     
        <button className="btn" type="submit"
            onClick={() => openModal("custom")}>
          Custom Feedback
        </button>
        <button className="btn" type="submit"  onClick={() => openModal("manual")}>
           Manual Feedback
        </button>
Enter fullscreen mode Exit fullscreen mode
 const { getAllReview, feedback, loading, setEditFeedback,isClientcustomEditing,isClientmanualEditing, 
      socket,user, openModal } =
    useAppContext()
Enter fullscreen mode Exit fullscreen mode

  const openModal = (value) => {
    dispatch({ type: OPEN_MODAL })

    if (value === "add") {
      dispatch({ type: CLOSE_CLIENT_MODAL })
    } 
    else if (value === "edittext") {
      dispatch({ type: OPEN_CLIENTTEXT_MODAL })
    } 
    else if (value === "custom") {
      dispatch({ type: OPEN_CLIENTCUSTOM_MODAL })
    } 
    else if (value === "manual") {
      dispatch({ type: OPEN_CLIENTMANUAL_MODAL })
    }     
    else {
      dispatch({ type: OPEN_CLIENT_MODAL })
    }
  }
Enter fullscreen mode Exit fullscreen mode
 if (action.type === OPEN_CLIENTCUSTOM_MODAL) {
    return { ...state, isModal: true, isClientEditing: false,isClientcustomEditing: true ,isClientmanualEditing: false}
  }
Enter fullscreen mode Exit fullscreen mode

{isClientcustomEditing ? <h6>Enter Answer</h6>:(<h6>Select Following option</h6>)}
Enter fullscreen mode Exit fullscreen mode

FormRow Validation

{isClientcustomEditing ? null:(<div style={{ display: 'flex', justifyContent: 'space-between', marginRight: '130px' }}>
                      <FormRow
                        type="radio" 
                        name="checktwo" 
                        value={feedback.answer_two}
                        handleChange={handleChange} 
                      />
                      <FormRow
                        type="text"
                        name="answertwo"

                        value={feedback.answer_two}
                        handleChange={handleChange}
                        disabled={isClientEditing}
                        placeholder="Enter Answer"
                      />
                     </div>)}

Enter fullscreen mode Exit fullscreen mode

button validation

{isClientEditing ? "Save" : "Submit"}
Enter fullscreen mode Exit fullscreen mode

checkbox validation


{editingClient.checktwo==null ? null:(<FormRow
                        type="text"                       
                        name="answerfour"                        
                        value={values.checktwo}
                        handleChange={handleChange}
                        disabled={isClientEditing}
                      />)}
Enter fullscreen mode Exit fullscreen mode

Country code with phone no validation

import PhoneInput from "react-phone-number-input"
import "react-phone-number-input/style.css"
import { PhoneNumberUtil } from "google-libphonenumber"
Enter fullscreen mode Exit fullscreen mode
 const [selectedCountry, setSelectedCountry] = useState("US")
Enter fullscreen mode Exit fullscreen mode
  const handleContactChange = (e) => {
    setValues({ ...values, ["contactNumber"]: e })
    validatePhoneNumber(e, selectedCountry)
  }
Enter fullscreen mode Exit fullscreen mode
const handleCountryChange = (country) => {
    setSelectedCountry(country)
    setValues({ ...values, ["country"]: country })

    validatePhoneNumber(values.contactNumber, country)
  }
Enter fullscreen mode Exit fullscreen mode
  const validatePhoneNumber = (input, country = selectedCountry) => {
    try {
      // Create an instance of PhoneNumberUtil
      const phoneUtil = PhoneNumberUtil.getInstance()

      // Parse the phone number
      const parsedNumber = phoneUtil.parseAndKeepRawInput(input, country)

      // Check if the phone number is valid for the selected country
      const isValidPhoneNumber = phoneUtil.isValidNumberForRegion(
        parsedNumber,
        country
      )

      setIsValid(isValidPhoneNumber)
    } catch (error) {
      // Handle any errors during phone number validation
      setIsValid(false)
    }
  }
Enter fullscreen mode Exit fullscreen mode
 <PhoneInput
                        international
                        defaultCountry={values.country || selectedCountry}
                        value={values.contactNumber}
                        onChange={handleContactChange}
                        country={values.country}
                        onCountryChange={handleCountryChange}
                      />
                      {isValid ? null : (
                        <span className="validatePError">
                          invalid phone number.
                        </span>
                      )}
Enter fullscreen mode Exit fullscreen mode

Email validation on keyup

import validator from "validator"
Enter fullscreen mode Exit fullscreen mode
const validateEmail = () => {
    if (validator.isEmail(values.email)) {
      setIsEmail(true)
    } else {
      setIsEmail(false)
    }
  }
Enter fullscreen mode Exit fullscreen mode
<FormRow
                        type="email"
                        name="email"
                        labelText="Email*"
                        value={values.email}
                        handleChange={handleChange}
                        disabled={isClientEditing}
                        onKeyUp={validateEmail}
                        required={true}
                        placeholder="Enter Email"
                      />
                      {isEmail ? null : (
                        <>
                          <span className="errordef">
                            please enter valid email
                          </span>
                        </>
                      )}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)