November 24, 2023

React Bootstrap Login Form With Validations

In this post we'll see how to create a login form with validations using React and Bootstrap 5. The login form has two fields- email and password and a submit button.

login form react

LoginForm React and Bootstrap Example

In this example Bootstrap 5 is used.

If you want to know how to download Bootstrap and use in your React application, check this post- Installing Bootstrap in React

Login.js

import { useState } from "react";

const Login = () => {
    const [formField, setState] = useState({
        email: '',
        passwd: '',
        errors: []
    });
    const handleInputChange = (event) => {
        let errors = [];
        // clear errors if any
        if (formField.errors.length > 0) {
            setState((prevState) => (
                {...prevState, errors}
            ));
        }
        const value = event.target.value;
        const name = event.target.name;
        setState((prevState) => (
            {...prevState, [name]: value}
        ));
    }
    const submitHandler = (event) => {
        event.preventDefault();
        let errors = [];
        //email regular expression pattern
        const emailRegEx = /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/;
        let isEmailValid = emailRegEx.test(formField.email.toLowerCase())
        
        if (!isEmailValid) {
            errors.push("email");
        }
        if(formField.passwd  === ""){
            errors.push("passwd");
        }

        setState((prevState) => (
            {...prevState, errors}
        ));
        // If there is error dont submit, return to form
        if (errors.length > 0) {
            return false;
        } else{
            // write code for successful submission...
            console.log('Form Submitted')
        }
    }

    const hasError = (name) => {
        //console.log("haserror " + name);
        return formField.errors.indexOf(name) !== -1;
    }

    return (
        <div className="card col-5 mt-5 mx-auto">
            <div className="card-header bg-info text-white">
            <h2>User Login</h2>
            </div>
            <div className="card-body">
                <form onSubmit={submitHandler}>
                    <div className="mb-3">
                        <label className="form-label" htmlFor="userEmail">Email</label>
                        <input type="text" 
                            className={hasError("email") ? "form-control is-invalid" :"form-control"}  
                            placeholder="Enter Email" 
                            name="email"
                            id="userEmail" 
                            value={formField.email} 
                            onChange={handleInputChange} />
                         <div className={hasError("email") ? "invalid-feedback" : ""}>
                            { hasError("email") ? <span>Please enter valid email</span> : "" }
                         </div>
                    </div>   
                    <div className="mb-3">
                        <label className="form-label" htmlFor="userPassword">Password</label>
                        <input type="password" 
                            className={hasError("passwd") ? "form-control is-invalid" :"form-control"}   
                            placeholder="Enter Password" 
                            name="passwd"
                            id="userPassword" 
                            value={formField.passwd} 
                            onChange={handleInputChange}/>
                        <div className={hasError("passwd") ? "invalid-feedback" : ""}>
                            { hasError("passwd") ? <span>Please enter password</span> : "" }
                         </div>
                    </div>  
                    <button type="submit" className="btn btn-primary">Submit</button> 
                </form>
            </div>
        </div>
    )
    
}

export default Login;

Some important points about the login form are as given below-

  1. Uses the Bootstrap card as a container for the form elements.
  2. Single state is used here with useState() hook. State is managed as an object with three properties email, passwd and an array of errors which keeps track of all the fields that fail validations. Initial state is empty string for email and passwd, empty array ([]) for errors.
  3. In input fields onChange() event handler is mapped to a single function handleInputChange() for all the fields. Note that a single setState() changes state for all the form fields. For that to work, ensure that the name you give to input fields matches the name of the properties in state object.
  4. When calling setState() to update state, spread operator is used to spread the previous state so that you can overwrite the individual fields without losing the data for other fields.
    setState((prevState) => (
        {...prevState, [name]: value}
    ));
    	
  5. Form onSubmit() event handler is mapped to submitHandler() function. That's where field validation is done and field name is pushed to errors array if field fails validation.
  6. While rendering, errors array is checked. If field exists in that array that means field failed validation.
  7. When the field fails validation Bootstrap class "is-invalid" is added which creates red border around the field. For error message "invalid-feedback" class is used. You don't need to write any css yourself.

Clicking submit without entering any values.

login form React Bootstrap

When only email is entered.

That's all for the topic React Bootstrap Login Form With Validations. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment