Form Validation in React

Expert-Level Explanation

Form validation in React is the process of ensuring the user inputs valid data into a form before submission. It can be implemented in both controlled and uncontrolled components. For controlled components, validation logic is typically executed during state updates. For uncontrolled components, validation might occur in the submit handler, using refs to access the form data.

Creative Explanation

Form validation is like a checkpoint before entering a concert. Each ticket (form input) is checked to make sure it's valid—not expired, for the right event, and not counterfeit. In React, this "checkpoint" can be checking text fields for proper format, ensuring selections are made, or verifying that inputs aren't left empty.

Practical Explanation with Code

An example of form validation in a controlled component:

import React, { useState } from 'react';

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

  const validateEmail = (e) => {
    setEmail(e.target.value);
    if (!e.target.value.includes('@')) {
      setEmailError('Please enter a valid email.');
    } else {
      setEmailError('');
    }
  };

  return (
    <form>
      <input type="text" value={email} onChange={validateEmail} />
      {emailError && <p>{emailError}</p>}
    </form>
  );
}

Real-World Example

In a user registration form on a social media website, form validation ensures that the username is not already taken, the email is in the correct format, and the password meets complexity requirements. This validation enhances the user experience by providing immediate feedback and preventing the submission of invalid or incomplete forms.

Did you find this article valuable?

Support InterviewPro: Master Tech Fundamentals by becoming a sponsor. Any amount is appreciated!