Alex5207
Alex5207

Reputation: 484

React-Bootstrap form validation - Need one function per field?

I am using the React-Bootstrap forms. I have around 15 fields that need to be filled out in the form. Does this mean I need to have 15 validation functions (e.g validateName, validateDate etc.)?

How is this generally approached?

My data looks something like this:

state = {
  person : {
     name: '',
     startDate: null,
     ...
     ...
     active: null
   }
 }

Upvotes: 2

Views: 5050

Answers (1)

Hemadri Dasari
Hemadri Dasari

Reputation: 33984

Say for eg you have 2 input fields

     state = {
       person : {
            name: '',
            age: 0
       },
       nameError: null,
       ageError: null
    }

    handleInput = e => {
        const { person } = this.state;
        person[e.target.name] = e.target.value;
        this.setState({
            person
        });
    }

    handleSubmit = () => {
       const { person } = this.state;
       if(person.name === null){
            this.setState({
                nameError: 'Name is required',
                ageError: null
            });
       }else if(person.age === 0){
            this.setState({
                ageError: 'Age is required',
                nameError: null
            });
       }else{
           //send the values to the backend
           //also reset both nameError and ageError here
       }      
    }

    render(){
          const { person, nameError, ageError } = this.state;
          return(
              <div>
                  <input type='text' name='name' value={person.name} onChange={e => this.handleInput(e)} />
                   {nameError}
                  <input type='number' name='age' value={person.age} onChange={e => this.handleInput(e)} />
                  {ageError}
                  <button value='Submit' onClick={this.handleSubmit} />
              </div>
          );
    }

Please Let me know if you have further queries. Sorry if there are any typos I answered on my mobile

Upvotes: 2

Related Questions