Problem Overview
Form validation is essential for ensuring user input is correct before submission. Here’s how to implement it in React:
- Set Up State: Use the
useStatehook to manage form data and errors. - Validation Logic: Create a function to validate inputs. For example, check if the email is in the correct format:
- Handle Submission: In the form’s onSubmit handler, call the validation function and set errors if validation fails:
const [formData, setFormData] = useState({ name: '', email: '' }); const validateEmail = (email) => /^[^
][ -]+@[a-zA-Z_]+? ?\.[a-zA-Z]{2,3}$/.test(email); const handleSubmit = (e) => { e.preventDefault(); if (!validateEmail(formData.email)) setErrors({ email: 'Invalid email' }); } By implementing these steps, you can create a responsive and user-friendly form validation system in your React applications.