-
Create Form Elements: Define the form and necessary input elements within a React component, such as
<input>,<select>, and<textarea>. -
Set Up State: Use
useStateto create state variables that store the values and validation status of input fields. -
Implement Validation Logic: Create functions to check if input data meets expectations (e.g., non-empty, correct format, length restrictions). These functions can be invoked in the
onChangeevent of input fields or theonSubmitevent of the form. -
Real-time Feedback: Use the
onChangeevent listener on input fields to invoke validation functions in real-time and update the state based on validation results, such as error messages. This can be achieved through conditional rendering of error messages. -
Submission Validation: Re-call all relevant validation functions in the
onSubmitevent of the form to ensure all data is valid prior to submission. If validation errors exist, prevent form submission and display error messages to the user. -
Utilize Third-party Libraries: Libraries such as Formik and React Hook Form can be used to simplify form handling and validation. These libraries provide more concise APIs for managing form state, handling submissions, and executing validation.
Here is a simple code example illustrating this process:
javascriptimport React, { useState } from 'react'; function FormComponent() { const [formData, setFormData] = useState({ username: '', age: 0, errors: { username: '', age: '' } }); const handleInputChange = (e) => { const { name, value } = e.target; setFormData({ ...formData, [name]: value }); // Call validation function validateField(name, value); }; const validateField = (name, value) => { let errors = formData.errors; switch (name) { case 'username': errors.username = value.length < 5 ? 'Username must be at least 5 characters long.' : ''; break; case 'age': errors.age = value < 18 ? 'You must be at least 18 years old.' : ''; break; default: break; } setFormData({ ...formData, errors }); }; const handleSubmit = (event) => { event.preventDefault(); // Validate all fields validateField('username', formData.username); validateField('age', formData.age); if (!formData.errors.username && !formData.errors.age) { console.log('Form is valid! Submitting...'); } else { console.log('Form is invalid! Please correct the errors.'); } }; return ( <form onSubmit={handleSubmit}> <div> <label>Username:</label> <input type="text" name="username" value={formData.username} onChange={handleInputChange} /> {formData.errors.username && <div>{formData.errors.username}</div>} </div> <div> <label>Age:</label> <input type="number" name="age" value={formData.age} onChange={handleInputChange} /> {formData.errors.age && <div>{formData.errors.age}</div>} </div> <button type="submit">Submit</button> </form> ); } export default FormComponent;
In this example, we create a simple form with username and age inputs, implementing both real-time and pre-submission validation.