Skip to main content

Form Validation and Handling

In this tutorial, we will explore form validation and handling techniques in real-world React applications. We'll cover controlled components, handling form submissions, and validation using a custom validation function.

Controlled Components

Controlled components allow us to manage form data using React state. Let's create a simple registration form with controlled components:

JavaScript
import React, { useState } from 'react';

function RegistrationForm() {
const [formData, setFormData] = useState({
username: '',
email: '',
password: '',
});

const handleChange = e => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};

return (
<form>
<div>
<label>Username:</label>
<input type="text" name="username" value={formData.username} onChange={handleChange} />
</div>
<div>
<label>Email:</label>
<input type="email" name="email" value={formData.email} onChange={handleChange} />
</div>
<div>
<label>Password:</label>
<input type="password" name="password" value={formData.password} onChange={handleChange} />
</div>
<button type="submit">Register</button>
</form>
);
}

export default RegistrationForm;

Here, we use the useState hook to store the form data and update the state using the handleChange function.

Handling Form Submission

Now, let's handle the form submission using the handleSubmit function:

JavaScript
// ...other imports and code

function RegistrationForm() {
// ...useState and handleChange

const handleSubmit = e => {
e.preventDefault();
console.log('Form data submitted:', formData);
};

return (
<form onSubmit={handleSubmit}>
{/* ...form fields */}
<button type="submit">Register</button>
</form>
);
}

export default RegistrationForm;

The handleSubmit function prevents the default form submission behavior using e.preventDefault() and logs the submitted data to the console.

Custom Validation

Let's add a custom validation function to validate the form data before submitting:

JavaScript
// ...other imports and code

function RegistrationForm() {
// ...useState and handleChange

const validateFormData = () => {
const errors = {};
if (!formData.username) errors.username = "Username is required";
if (!formData.email) errors.email = "Email is required";
if (!formData.password) errors.password = "Password is required";

return errors;
};

const handleSubmit = (e) => {
e.preventDefault();
const errors = validateFormData();

if (Object.keys(errors).length === 0) {
console.log("Form data submitted:", formData);
} else {
console.log("Form errors:", errors);
}
};

return (
// ...form JSX
);
}

export default RegistrationForm;

The validateFormData function checks if the form data is valid and returns an object with error messages for each invalid field. In handleSubmit, we check if the errors object is empty before submitting the form data.

Now you know how to handle form submissions and validate form data in real-world React applications. You can expand this approach to handle more complex validation rules and display error messages to the user.

Displaying Error Messages

Let's display error messages to the user when there's an error in their form input:

JavaScript
import React, { useState } from 'react';

function RegistrationForm() {
const [formData, setFormData] = useState({
username: '',
email: '',
password: '',
});
const [formErrors, setFormErrors] = useState({});

// ...handleChange, validateFormData, handleSubmit

return (
<form onSubmit={handleSubmit}>
<div>
<label>Username:</label>
<input type="text" name="username" value={formData.username} onChange={handleChange} />
{formErrors.username && <span>{formErrors.username}</span>}
</div>
<div>
<label>Email:</label>
<input type="email" name="email" value={formData.email} onChange={handleChange} />
{formErrors.email && <span>{formErrors.email}</span>}
</div>
<div>
<label>Password:</label>
<input type="password" name="password" value={formData.password} onChange={handleChange} />
{formErrors.password && <span>{formErrors.password}</span>}
</div>
<button type="submit">Register</button>
</form>
);
}

export default RegistrationForm;

We've added a new state variable formErrors to store the form errors. We update the formErrors state in the handleSubmit function with the returned errors from validateFormData. Then, we display the error messages for each field below the input field if there's an error.

Conclusion

This tutorial covered form validation and handling techniques in real-world React applications. You can now create and validate forms in your React applications with ease. Don't forget to style the error messages and form elements according to your application's design.