Validating Form Input

You can validate form input when the user is typing or you can wait untill the form gets submitted.

Example:

When you fill in your age, you will get an alert if the age field is not numeric:

class MyForm extends React.Component {  constructor(props) {    super(props);    this.state = {      username: '',      age: null,    };  }  myChangeHandler = (event) => {    let nam = event.target.name;    let val = event.target.value;    if (nam === "age") {      if (!Number(val)) {        alert("Your age must be a number");      }    }    this.setState({[nam]: val});  }  render() {    return (      <form>      <h1>Hello {this.state.username} {this.state.age}</h1>      <p>Enter your name:</p>      <input        type='text'        name='username'        onChange={this.myChangeHandler}      />      <p>Enter your age:</p>      <input        type='text'        name='age'        onChange={this.myChangeHandler}      />      </form>    );  }} ReactDOM.render(<MyForm />, document.getElementById('root'));  

Below you will see the same example as above, but the validation is done when the form gets submitted instead of when you write in the field.

Example:

Same example, but with the validation at form submit:

class MyForm extends React.Component {  constructor(props) {    super(props);    this.state = {      username: '',      age: null,    };  }  mySubmitHandler = (event) => {    event.preventDefault();    let age = this.state.age;    if (!Number(age)) {      alert("Your age must be a number");    }  }  myChangeHandler = (event) => {    let nam = event.target.name;    let val = event.target.value;    this.setState({[nam]: val});  }  render() {    return (      <form onSubmit={this.mySubmitHandler}>      <h1>Hello {this.state.username} {this.state.age}</h1>      <p>Enter your name:</p>      <input        type='text'        name='username'        onChange={this.myChangeHandler}      />      <p>Enter your age:</p>      <input        type='text'        name='age'        onChange={this.myChangeHandler}      />      <br/>      <br/>      <input type='submit' />      </form>    );  }} ReactDOM.render(<MyForm />, document.getElementById('root'));        

Adding Error Message

Error messages in alert boxes can be annoying, so let's make an error message that is empty by default, but displays the error when the user inputs anything invalid:

Example:

When you fill in your age as not numeric, an error message is dispalyed:

class MyForm extends React.Component {  constructor(props) {    super(props);    this.state = {      username: '',      age: null,      errormessage: ''    };  }  myChangeHandler = (event) => {    let nam = event.target.name;    let val = event.target.value;    let err = '';    if (nam === "age") {      if (val !="" && !Number(val)) {        err = <strong>Your age must be a number</strong>;      }    }    this.setState({errormessage: err});    this.setState({[nam]: val});  }  render() {    return (      <form>      <h1>Hello {this.state.username} {this.state.age}</h1>      <p>Enter your name:</p>      <input        type='text'        name='username'        onChange={this.myChangeHandler}      />      <p>Enter your age:</p>      <input        type='text'        name='age'        onChange={this.myChangeHandler}      />      {this.state.errormessage}      </form>    );  }} ReactDOM.render(<MyForm />, document.getElementById('root'));      

Textarea

The textarea element in React is slightly different from ordinary HTML.

In HTML the value of a textarea was the text between the start tag <textarea> and the end tag </textarea>, in React the value of a textarea is placed in a value attribute:

Example:

A simple textarea with some content initialized in the constructor:

class MyForm extends React.Component {  constructor(props) {    super(props);    this.state = {      description: 'The content of a textarea goes in the value attribute'    };  }  render() {    return (      <form>      <textarea value={this.state.description} />      </form>    );  }} ReactDOM.render(<MyForm />, document.getElementById('root'));  

Select

A drop down list, or a select box, in React is also a bit different from HTML.

in HTML, the selected value in the drop down list was defined with the selected attribute:

HTML:

<select>  <option value="Ford">Ford</option>  <option value="Volvo" selected>Volvo</option>  <option value="Fiat">Fiat</option></select>

 

In React, the selected value is defined with a value attribute on the select tag:

Example:

A simple select box, where the selected value "Volvo" is initialized in the constructor:

class MyForm extends React.Component {  constructor(props) {    super(props);    this.state = {      mycar: 'Volvo'    };  }  render() {    return (      <form>      <select value={this.state.mycar}>        <option value="Ford">Ford</option>        <option value="Volvo">Volvo</option>        <option value="Fiat">Fiat</option>      </select>      </form>    );  }} ReactDOM.render(<MyForm />, document.getElementById('root'));