🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Expert Masterclasses.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEreact

react Documentation

LOADING ENGINE...

React Form Validation

Master React components, hooks, and best practices.

Form Validation

Author

Pascual Vila

Frontend Instructor.

Form validation is essential to ensure that user-entered data is correct before submitting it to the server. React facilitates form validation by using states and conditionals.

Basic Validation in React:

To perform basic validation, you can check the values entered by the user and display error messages based on the conditions.

      {`import React, { useState } from "react";

      function FormWithValidation() {
        const [email, setEmail] = useState("");
        const [error, setError] = useState("");

        const handleSubmit = (event) => {
          event.preventDefault();
          if (!email.includes("@")) {
            setError("Email must contain '@'.");
          } else {
            setError("");
            alert("Form submitted");
          }
        };

        return (
          <form onSubmit={handleSubmit}>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="Enter your email"
            />
            {error && <p className="text-red-500">{error}</p>}
            <button type="submit">Submit</button>
          </form>
        );
      }

      export default FormWithValidation;`}