Validation using HTML5 Attributes and Custom Validation in React JS
Form validation is an essential aspect of any web application to ensure data integrity and enhance user experience. React allows you to integrate HTML5 form validation attributes as well as implement custom validation logic. In this article, we will explore both HTML5 validation attributes and custom validation in React forms.
HTML5 Form Validation in React
HTML5 provides built-in validation for form elements such as <input>
, <select>
, and <textarea>
. These elements come with several validation attributes that help ensure the data entered by users is valid.
Common HTML5 Validation Attributes
required
: Specifies that an input field must be filled out before submitting the form.minlength
andmaxlength
: Define the minimum and maximum number of characters allowed for a text input.pattern
: Defines a regular expression that the input value must match.type
: Specifies the type of data (e.g.,email
,number
,url
, etc.).min
andmax
: Set the range for number inputs.
Example: HTML5 Validation in a React Form
Here’s an example of using HTML5 attributes for validation in a React functional component:
import React, { useState } from 'react';
function HTML5ValidationForm() {
const [formData, setFormData] = useState({
name: '',
email: '',
password: '',
});
const handleChange = (event) => {
const { name, value } = event.target;
setFormData({
...formData,
[name]: value,
});
};
const handleSubmit = (event) => {
event.preventDefault();
if (event.target.checkValidity()) {
alert('Form submitted successfully!');
} else {
alert('Please fill in the required fields correctly.');
}
};
return (
);
}
export default HTML5ValidationForm;
Explanation:
- In this form, each
<input>
field uses HTML5 attributes likerequired
,minLength
, andpattern
to ensure the user enters valid data. - The
checkValidity()
method is used in thehandleSubmit
function to check if all the form fields are valid based on the HTML5 attributes. - If the form is valid, we show an alert confirming submission; otherwise, we prompt the user to fill out the fields correctly.
Custom Validation in React
Although HTML5 attributes provide a basic level of validation, there are cases where you may need to implement custom validation logic. Custom validation gives you full control over how data is validated before being submitted. In React, custom validation can be added using state and event handlers.
Example: Custom Validation for Email and Password
Let’s create a form where we validate the email format and password strength using custom logic:
import React, { useState } from 'react';
function CustomValidationForm() {
const [formData, setFormData] = useState({
email: '',
password: '',
});
const [errors, setErrors] = useState({
email: '',
password: '',
});
const handleChange = (event) => {
const { name, value } = event.target;
setFormData({
...formData,
[name]: value,
});
};
const validateEmail = (email) => {
const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
return regex.test(email);
};
const validatePassword = (password) => {
return password.length >= 6;
};
const handleSubmit = (event) => {
event.preventDefault();
let emailError = '';
let passwordError = '';
if (!validateEmail(formData.email)) {
emailError = 'Please enter a valid email.';
}
if (!validatePassword(formData.password)) {
passwordError = 'Password must be at least 6 characters long.';
}
if (emailError || passwordError) {
setErrors({ email: emailError, password: passwordError });
} else {
setErrors({ email: '', password: '' });
alert('Form submitted successfully!');
}
};
return (
);
}
export default CustomValidationForm;
Explanation:
- The
validateEmail
function checks if the email is in the correct format using a regular expression. - The
validatePassword
function ensures that the password is at least 6 characters long. - If validation fails, error messages are displayed under the respective input fields.
- If both validations pass, the form is submitted successfully.
Conclusion
Validation is a critical part of form handling in React. While HTML5 attributes provide simple and effective client-side validation for many common cases, React also allows for custom validation logic to handle more complex validation requirements. By combining both methods, you can ensure that your forms provide a seamless and reliable user experience.