How to validate form in ReactJS?

In this tutorial we will use props, state, constructor, events in reactjs.

First of all create your component like Signup and extend it from Component Class (Import Component From react).

Now, Add Constructor to our component.
Create a function han…


This content originally appeared on DEV Community and was authored by Chetan Rohilla

In this tutorial we will use props, state, constructor, events in reactjs.

First of all create your component like Signup and extend it from Component Class (Import Component From react).

  • Now, Add Constructor to our component.
  • Create a function handleChange that will trigger on change of form field.
  • Create a function handleSubmit that will trigger on form submit.
  • Show the errors on Template inside render method and Create Form.

Here below is complete code.

import { Component } from "react";

class Signup extends Component {

    constructor(props) {
        super(props);
        this.state = {
            fullName: null,
            email: null,
            password: null,
            errors: {
                fullName: '',
                email: '',
                password: '',
            }
        };
    }


    handleChange = (event) => {

        event.preventDefault();

        const validEmailRegex =
            RegExp(/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i);

        const { name, value } = event.target;
        let errors = this.state.errors;

        switch (name) {
            case 'fullName':
                errors.fullName =
                    value.length < 5
                        ? 'Full Name must be 5 characters long!'
                        : '';
                break;
            case 'email':
                errors.email =
                    validEmailRegex.test(value)
                        ? ''
                        : 'Email is not valid!';
                break;
            case 'password':
                errors.password =
                    value.length < 8
                        ? 'Password must be 8 characters long!'
                        : '';
                break;
            default:
                break;
        }

        this.setState({ errors, [name]: value }, () => {
            console.log(errors)
        })
    }


    handleSubmit = (event) => {

        event.preventDefault();

        const validateForm = (errors) => {
            let valid = true;
            Object.values(errors).forEach(
                // if we have an error string set valid to false
                (val) => val.length > 0 && (valid = false)
            );
            return valid;
        }

        if (validateForm(this.state.errors)) {
            console.info('Valid Form')
        } else {
            console.error('Invalid Form')
        }
    }


    render() {
        console.log(this.props);
        return ( 
            <div>
                <form onSubmit={(event) => this.handleSubmit(event)}>
                    <input type="text" name="fullName" onChange={(event) => this.handleChange(event)} />
                    {errors.fullName.length > 0 &&
                        <span className='error'>{errors.fullName}</span>}

                    <input type="email" name="email" onChange={(event) => this.handleChange(event)}/>
                    {errors.email.length > 0 &&
                        <span className='error'>{errors.email}</span>}

                    <input type="password" name="password" onChange={(event) => this.handleChange(event)}/>

                    {errors.password.length > 0 &&
                        <span className='error'>{errors.password}</span>}

                    <input type="submit" name="submit" />
                </form>

            </div>

        );
    }
}

export default Signup;

Please like share subscribe and give positive feedback to motivate me to write more for you.

For more tutorials please visit my website.

Thanks:)
Happy Coding:)


This content originally appeared on DEV Community and was authored by Chetan Rohilla


Print Share Comment Cite Upload Translate Updates
APA

Chetan Rohilla | Sciencx (2022-03-24T14:06:49+00:00) How to validate form in ReactJS?. Retrieved from https://www.scien.cx/2022/03/24/how-to-validate-form-in-reactjs/

MLA
" » How to validate form in ReactJS?." Chetan Rohilla | Sciencx - Thursday March 24, 2022, https://www.scien.cx/2022/03/24/how-to-validate-form-in-reactjs/
HARVARD
Chetan Rohilla | Sciencx Thursday March 24, 2022 » How to validate form in ReactJS?., viewed ,<https://www.scien.cx/2022/03/24/how-to-validate-form-in-reactjs/>
VANCOUVER
Chetan Rohilla | Sciencx - » How to validate form in ReactJS?. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/03/24/how-to-validate-form-in-reactjs/
CHICAGO
" » How to validate form in ReactJS?." Chetan Rohilla | Sciencx - Accessed . https://www.scien.cx/2022/03/24/how-to-validate-form-in-reactjs/
IEEE
" » How to validate form in ReactJS?." Chetan Rohilla | Sciencx [Online]. Available: https://www.scien.cx/2022/03/24/how-to-validate-form-in-reactjs/. [Accessed: ]
rf:citation
» How to validate form in ReactJS? | Chetan Rohilla | Sciencx | https://www.scien.cx/2022/03/24/how-to-validate-form-in-reactjs/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.