Enhancing Your Registration Form with Validation in React

Enhancing Your Registration Form with Validation in React

In this blog, we will enhance our existing `RegistrationForm` component by adding required field validation and displaying error messages if the user tries to submit the form without filling out all fields. This feature will help ensure that the form is completed correctly before submission.

Starting Point

We will start with the `RegistrationForm` component that has been styled using CSS Modules. Our goal is to implement validation logic that checks each input field (name, email, password) to ensure they are not left blank.

Step 1: Updating the Component with Validation Logic

We need to update our form handling logic to include validation when the form is submitted. Here’s how you can implement this:

Update the `RegistrationForm.js` File

Modify your `RegistrationForm` component to include validation checks:

				
					import React, { useState } from 'react';
import styles from './Registration.module.css';

function RegistrationForm() {
    const [user, setUser] = useState({
        name: '',
        email: '',
        password: ''
    });
    const [errors, setErrors] = useState({});

    const handleSubmit = event => {
        event.preventDefault();
        let newErrors = {};
        // Validation rules
        if (!user.name) newErrors.name = 'Name is required';
        if (!user.email) newErrors.email = 'Email is required';
        if (!user.password) newErrors.password = 'Password is required';

        if (Object.keys(newErrors).length > 0) {
            setErrors(newErrors);
        } else {
            console.log('Form is valid! Submitting...');
            // Submit form logic here
        }
    };

    const handleChange = (field, value) => {
        setUser({...user, [field]: value});
        // Clear errors for specific field
        if (!!errors[field]) setErrors({...errors, [field]: null});
    };

    return (
        <div className={styles.formContainer}>
            <form className={styles.registerForm} onSubmit={handleSubmit}>
                <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="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: Update the CSS Module for Error Styling

Next, enhance your `Registration.module.css` to include styles for error handling:

				
					.formContainer {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

.registerForm {
    display: flex;
    flex-direction: column;
}

.formField, .inputError {
    margin-bottom: 20px;
    padding: 10px;
    font-size: 16px;
    width: 300px;
    border-radius: 5px;
    border: 1px solid #ddd;
}

.inputError {
    border-color: red;
}

.errorMessage {
    color: red;
    font-size: 14px;
    margin-bottom: 5px;
}

				
			

By integrating field validation and error message displays into your `RegistrationForm`, you’ve significantly improved the form’s usability and ensured that user input is validated before submission. This practice not only enhances the user experience but also prevents potential issues from incomplete or incorrect data submissions.

 

 

 

Overview

Leave a Reply

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

Enquire Now