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
Click to Enlarge