Advanced Validation Techniques for Your React Registration Form

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 (
        <div className={styles.formContainer}>
            <form className={styles.registerForm} onSubmit={handleSubmit}>
                {Object.keys(errors).length === 0 && user.name ? <div className={styles.successMessage}>Form is valid!</div> : null}
                <input
                    type="text"
                    value={user.name}
                    onChange={(e) => handleChange('name', e.target.value)}
                    className={errors.name ? styles.inputError : styles.formField}
                    placeholder="Name"
                />
                {errors.name && <span className={styles.errorMessage}>{errors.name}</span>}
                <input
                    type="email"
                    value={user.email}
                    onChange={(e) => handleChange('email', e.target.value)}
                    className={errors.email ? styles.inputError : styles.formField}
                    placeholder="Email"
                />
                {errors.email && <span className={styles.errorMessage}>{errors.email}</span>}
                <input
                    type="text"
                    value={user.phone}
                    onChange={(e) => handleChange('phone', e.target.value)}
                    className={errors.phone ? styles.inputError : styles.formField}
                    placeholder="Phone"
                />
                {errors.phone && <span className={styles.errorMessage}>{errors.phone}</span>}
                <input
                    type="password"
                    value={user.password}
                    onChange={(e) => handleChange('password', e.target.value)}
                    className={errors.password ? styles.inputError : styles.formField}
                    placeholder="Password"
                />
                {errors.password && <span className={styles.errorMessage}>{errors.password}</span>}
                <button className={styles.formField} type="submit">
                    Register
                </button>
            </form>
        </div>
    );
}

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

				
			

Overview

Leave a Reply

Your email address will not be published. Required fields are marked *

Enquire Now