Advanced Validation Techniques for Your React Registration Form
Enhancements Overview
We will update the RegistrationForm
to include:
- A new phone field with validation to ensure it contains only numbers.
- Enhanced email validation to check for a proper email format.
- Password validation to ensure it is at least 8 characters long and includes at least one number and one alphabet.
Step 1: Updating the Component with New Fields and Validations
Let’s add the new fields and update our validation logic.
Update the RegistrationForm.js
File
Adjust your RegistrationForm
component to include the new fields and their corresponding validations:
import React, { useState } from 'react';
import styles from './Registration.module.css';
function RegistrationForm() {
const [user, setUser] = useState({
name: '',
email: '',
phone: '',
password: ''
});
const [errors, setErrors] = useState({});
const handleSubmit = event => {
event.preventDefault();
let newErrors = validateForm(user);
if (Object.keys(newErrors).length > 0) {
setErrors(newErrors);
} else {
console.log('Form is valid! Submitting...');
// Here you would handle form submission, such as sending data to a server
}
};
const handleChange = (field, value) => {
setUser({...user, [field]: value});
if (!!errors[field]) setErrors({...errors, [field]: null});
};
function validateForm(fields) {
let errors = {};
if (!fields.name) errors.name = 'Name is required';
if (!fields.email) {
errors.email = 'Email is required';
} else if (!/\S+@\S+\.\S+/.test(fields.email)) {
errors.email = 'Email address is invalid';
}
if (!fields.phone) {
errors.phone = 'Phone is required';
} else if (!/^\d{10}$/.test(fields.phone)) {
errors.phone = 'Phone number is invalid';
}
if (!fields.password) {
errors.password = 'Password is required';
} else if (!/(?=.*\d)(?=.*[a-zA-Z]).{8,}/.test(fields.password)) {
errors.password = 'Password must be at least 8 characters and include at least one number and one alphabet';
}
return errors;
}
return (
);
}
export default RegistrationForm;
Step 2: Style Adjustments in CSS Module
Make sure your Registration.module.css
file includes styles that visually indicate error states:
.formContainer {
display: flex;
justify