0

I'm trying to validate each input field. Assuming I have 5 input fields, how do I set 'error' state for each input field. For example, this.setState({error['roleShortName'] : true }), This won't work and in input, invalid={this.state.error["roleShortName"]}.

<FormGroup row>
      <Label for="roleshortname" sm={4}>roleshortname</Label>
            <Col sm={8}>
                 <Input invalid={this.state.error}
                      autoComplete='off'
                      onChange={this.handleChange}
                      type="text"
                      value={this.state.roleShortName}
                      name="roleShortName"
                      />
             </Col>
</FormGroup>

<FormGroup row>
     <Label for="rolefullname" sm={4}>rolefullname</Label>
            <Col sm={8}>
                  <Input invalid={this.state.error}
                   autoComplete='off'
                   onChange={this.handleChange}
                   type="text"
                   value={this.state.roleName}
                   name="roleName"
              </Col>
</FormGroup>
<Button onClick={() => this.handleAddConfirm()}
handleAddConfirm() {

        if (!this.state.roleShortName) {
            this.setState({ error: true })
            return
        }
        else if (!this.state.roleName) {
            this.setState({error: true})
            return
        }
Alvin Mathis
  • 110
  • 1
  • 10
  • `this.setState({error['roleShortName'] : true })` is this code not working for you ? – Milind Agrawal Feb 24 '20 at 07:12
  • No it's not working. it's saying ' : ' expected or I'm doing it wrong? :( – Alvin Mathis Feb 24 '20 at 07:15
  • Does this answer your question? [Variable as the property name in a JavaScript object literal?](https://stackoverflow.com/questions/11043026/variable-as-the-property-name-in-a-javascript-object-literal) – jonrsharpe Feb 24 '20 at 07:31

3 Answers3

1

this.setState({error['roleShortName']: true}) won't work. If you want the key to be dynamic, here's how it should look like:

this.setState({[error['roleShortName']]: true})

Notice the [] surrounding the key name.

Edit: I think you're looking for a dictionary to hold an error for each input:

handleAddConfirm() {
        var newErrors = {...this.state.errors}
        if (!this.state.roleShortName) {
            newErrors["roleShortName"] = true
        }
        else if (!this.state.roleName) {
            newErrors["roleName"] = true
        }
        this.setState({ errors: newErrors })
        return
}

In your constructor, you should have

this.state = {errors: {}}
AdamGold
  • 4,941
  • 4
  • 29
  • 47
  • I'm sorry I'm new to this stuff, I'm getting error is undefined here, where and how do I define it? – Alvin Mathis Feb 24 '20 at 07:37
  • I don't think what you're looking for is dynamic key names. I think you want a dictionary to hold your errors for each input. See me updated answer. – AdamGold Feb 24 '20 at 07:45
0

Here's something general provided your input field has a name attribute.

You pick up the name from preferably blur event and set the value of error to it.

[e.target.name] = [e.target.value]

In your case, in the error object just set the name property and value like this

// check for error on `e.target.name` field and if true

this.setState({ error[e.target.name]: true } )
HalfWebDev
  • 7,022
  • 12
  • 65
  • 103
0

Initialise an object in constructor which will hold error state of each input fields.

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

<Input invalid={this.state.errorFields.roleShortName}
       autoComplete='off'
       onChange={this.handleChange}
       type="text"
       value={this.state.roleShortName}
       name="roleShortName"
/>

    handleChange(e) {
      const { name, value } = e.target;
      let errorFields = this.state.errorFields;
      errorFields[name] = false;
      if (!value) {
        errorFields[name] = true;    
      }
      this.setState({
       errorFields,
       [name]: value
      });
    }

Then in handleAddConfirm function.

handleAddConfirm(e) {
   let indexOfInvalidState Object.values(this.state.errorFields).indexOf(true);
   if (indexOfInvalidState > -1) {
      return false;
   }
}
kuns
  • 44
  • 3