Apply regex to reactJs Forms.

Apply regex to reactJs Forms.

Here is a new version of the complex form example that includes regex patterns to check different form fields:

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';
    } else if (!/^\S+@\S+\.\S+$/.test(formData.email)) {
      errors.email = 'Invalid email format';
    }

    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}>
        <label>
          First Name:
          <input
            type="text"
            name="firstName"
            value={formData.firstName}
            onChange={handleInputChange}
          />
        </label>
        {formErrors.firstName && <p style={{ color: 'red' }}>{formErrors.firstName}</p>}

        <label>
          Last Name:
          <input
            type="text"
            name="lastName"
            value={formData.lastName}
            onChange={handleInputChange}
          />
        </label>
        {formErrors.lastName && <p style={{ color: 'red' }}>{formErrors.lastName}</p>}

        <label>
          Email:
          <input
            type="email"
            name="email"
            value={formData.email}
            onChange={handleInputChange}
          />
        </label>
        {formErrors.email && <p style={{ color: 'red' }}>{formErrors.email}</p>}

        <label>
          Password:
          <input
            type="password"
            name="password"
            value={formData.password}
            onChange={handleInputChange}
          />
        </label>
        {formErrors.password && <p style={{ color: 'red' }}>{formErrors.password}</p>}

        <label>
          Bio:
          <textarea name="bio" value={formData.bio} onChange={handleInputChange} />
        </label>
        {formErrors.bio && <p style={{ color: 'red' }}>{formErrors.bio}</p>}

        <label>
          Gender:
          <div>
            <label>
              <input
                type="radio"
                name="gender"
                value="male"
                checked={formData.gender === 'male'}
                onChange={handleInputChange}
              />
              Male
            </label>
            <label>
              <input
                type="radio"
                name="gender"
                value="female"
                checked={formData.gender === 'female'}
                onChange={handleInputChange}
              />
              Female
            </label>
          </div>
        </label>
        {formErrors.gender && <p style={{ color: 'red' }}>{formErrors.gender}</p>}

        <label>
          Agree to Terms:
          <input
            type="checkbox"
            name="agreeTerms"
            checked={formData.agreeTerms}
            onChange={handleInputChange}
          />
        </label>
        {formErrors.agreeTerms && <p style={{ color: 'red' }}>{formErrors.agreeTerms}</p>}

        <label>
          Country:
          <select name="country" value={formData.country} onChange={handleInputChange}>
            <option value="Select Country" disabled>
              Select Country
            </option>
            <option value="USA">USA</option>
            <option value="Canada">Canada</option>
            <option value="UK">UK</option>
          </select>
        </label>
        {formErrors.country && <p style={{ color: 'red' }}>{formErrors.country}</p>}

        <button type="submit">Submit</button>
      </form>
    </div>
  );
};

export default ComplexForm;

In this example, each input field connects to its matching validation error message. If there's an error, the message shows up in red text. The regex patterns for email validation (/^\S+@\S+\.\S+$/) and password validation (at least 6 characters) stay the same. Change the regex patterns and error messages to fit your own validation needs.

Did you find this article valuable?

Support LingarajTechhub by becoming a sponsor. Any amount is appreciated!