How to create validation on select dropdown input field in react

How to create validation on select dropdown input field in react

Posted by Luke Beeno on January 18, 2022

How to create validation on select dropdown input field in react

How to create validation on select dropdown input field in react

Posted by Luke Beeno on January 18, 2022

From time to time, you may want to validate your form input fields. This is mainly to ensure that the right data is being collected.

In this lesson you will be shown how to validate the select field in react. A class component will be used to demonstrate this, however it should not be too hard to translate to a function component.

Please be sure to have a working react project before continuing. If you need help in order to understand how to set up a react project, go here

Step 1. Install dependencies

npm installĀ  react-select simple-react-validator react-bootstrap

Step 2. Import dependencies

import Select from "react-select";
import SimpleReactValidator from "simple-react-validator";
import {Form} from "react-bootstrap";

Step 3. Add states and methods to constructor

The state profession holds selected value

The state onSubmit  is a flag to indicate if the user click submit

The variable validator holds a instance of simple-react-validator

The variable handleSubmit binds the method handleSubmit to the class. This method will be added in the following steps.

constructor(props) {
  this.state = {
  this.validator = new SimpleReactValidator();
  this.handleSubmit = this.handleSubmit.bind(this);

Step 4. Add array

This array will be used to populate the select field

profession = [{value:'lawyer', label:'lawyer'}, {value:'reporter', label:'reporter'}];

Step 5. Add handleSubmit method

On submit, this method will check if the data is valid and if not will through an error below select field and highlight it red.

handleSubmit(event) {
  this.setState({onSubmit: true});

  if (this.validator.allValid()) {
    const { permission } = this.state;
    //if data valid, continue here;
  } else {
    this.setState({submitLoader: false});
    this.forceUpdate(); += " was-validated";

Step 6. Add onChange method

This method will run once the user selects a value in the select field options and store the value in the profession state.

It takes 2 params, one is the name of the field and one is the value of the field. In case there is more than one select field in your form, this one method can be used for all of them. 

It will also switch the on onSubmit state to false.

onChangeSelect(value, e){
  this.setState({onSubmit: false});

Step 7. Add styling to top of render method

This styling will be applied if there is a validation error.

const customStyles = {
  control: (base) => ({
    // state.isFocused can display different borderColor if you need it
    // overwrittes hover style
    '&:hover': {
      borderColor: '#a80000'

Step 8. Add form to render method

This should be the final piece. A form with only the select field as input.

<div className="container">
  <div className="col-4 mx-auto mt-5">
    <Form onSubmit={this.handleSubmit} className="needs-validation" noValidate>
           <Select placeholder="Select profession" name="profession" value={(this.state.profession !== "")?{label:this.state.profession}:"" || ""} options={this.profession} onChange={(e)=>this.onChangeSelect("profession", e)} styles={(this.state.profession === "" && this.state.onSubmit)?customStyles:""} required outline/>
                <div className="text-danger is-in-focus mt-1">{this.validator.message('profession', this.state.profession, 'required')}</div>
       <button type="submit" className="btn btn-primary mt-3">Submit</button>

That is all! This is a simple illustration of having a react select validation on the front end, so take it, improve on it and make it your own. I hope this lesson was helpful.

This field is required
Your question have been successfully submitted and will be reviewed before published
Please login to ask a question