How to validate ReactJs validate?

How to validate ReactJs validate?

Checking user input in React forms makes sure it follows some rules before sending the form. We can change the example to have basic form checks. In this case, I'll add easy checks like needed fields and the shortest password length. You can change these checks for your own needs.

import React, { useState } from 'react';

const ComplexForm = () => {
  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    email: '',
    password: '',
    bio: '',
    gender: '',
    agreeTerms: false,
    country: 'Select Country'
  });

  const [formErrors, setFormErrors] = useState({});

  const validateForm = () => {
    const errors = {};

    // Validate required fields
    if (!formData.firstName.trim()) {
      errors.firstName = 'First Name is required';
    }

    if (!formData.lastName.trim()) {
      errors.lastName = 'Last Name is required';
    }

    if (!formData.email.trim()) {
      errors.email = 'Email is required';
    }

    if (!formData.password.trim()) {
      errors.password = 'Password is required';
    } else if (formData.password.length < 6) {
      errors.password = 'Password must be at least 6 characters';
    }

    if (!formData.bio.trim()) {
      errors.bio = 'Bio is required';
    }

    if (!formData.gender) {
      errors.gender = 'Gender is required';
    }

    if (!formData.agreeTerms) {
      errors.agreeTerms = 'Please agree to the terms';
    }

    if (formData.country === 'Select Country') {
      errors.country = 'Please select a country';
    }

    setFormErrors(errors);

    return Object.keys(errors).length === 0; // Returns true if there are no errors
  };

  const handleInputChange = (event) => {
    const { name, value, type, checked } = event.target;

    setFormData((prevData) => ({
      ...prevData,
      [name]: type === 'checkbox' ? checked : value
    }));
  };

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

    // Validate the form
    const isValid = validateForm();

    if (isValid) {
      // Perform form submission action (e.g., send data to server)
      console.log('Form submitted:', formData);
      // Reset form fields
      setFormData({
        firstName: '',
        lastName: '',
        email: '',
        password: '',
        bio: '',
        gender: '',
        agreeTerms: false,
        country: 'Select Country'
      });

      // Reset form errors
      setFormErrors({});
    }
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        {/* ... (input fields) */}

        {/* Display validation errors */}
        {Object.keys(formErrors).length > 0 && (
          <div style={{ color: 'red' }}>
            <h2>Form Errors:</h2>
            <ul>
              {Object.values(formErrors).map((error, index) => (
                <li key={index}>{error}</li>
              ))}
            </ul>
          </div>
        )}

        <button type="submit">Submit</button>
      </form>

      {/* Display submitted data */}
      {/* ... */}
    </div>
  );
};

export default ComplexForm;

In this example, the validateForm function checks the form before submitting it. It looks for different conditions, and if there are any errors, it changes the formErrors state. The validation errors show up below the form. Change the validation rules based on your needs.