Articles → REACT.JS → Apply Validations On Form Element In React.Js

Apply Validations On Form Element In React.Js






Example






import React, { Component } from 'react';
import ReactDOM from 'react-dom'

class FormComponent extends React.Component {

    constructor(props) {
        super(props);
        this.state = { name: '' };

    }

   

    myChangeHandler = (event) => {
        this.setState({ name: event.target.value });

        
        
    }

    mySubmitHandler = (event) => {
        if (this.state.name.length > 5) {
            event.preventDefault();
            alert("length is more");
            return;
        }
        alert("You are submitting " + this.state.name);
    }

    render() {
        return (
            <form onSubmit={this.mySubmitHandler}>
                Name: <input type="text" name="txtName" onChange={this.myChangeHandler}/>
                <input type="submit" value="Click Me" />
            </form>
        );
    }
}

ReactDOM.render(<FormComponent />, document.getElementById('root'));



Output


Picture showing how the validation is applied in react.js
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Thursday, August 19, 2021

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250