Home > Mobile >  React validation using Material UI's TextField components
React validation using Material UI's TextField components

Time:11-03

I have been researching this for an hour now, and doesnt seem like there is much examples on this on the internet. I am trying to validate the input fields so that all fields are filled, otherwise there will be an error. Amount of characters doesnt matter, just need to fill the inputs.

So here is my state object

constructor(props) {
    super(props);
    this.state = {
      firstName: '',
      lastName: '',
      ...,
    
    };
  }

And here are the material ui textfields

<TextField
                className={classes.formInput}
                name="firstName"
                onChange={e => this.handleChange(e.target.value)}
                required
                id=""
                type="text"
                InputLabelProps={{
                  shrink: true,
                }}
                error={!firstName}
                helperText="Name is required"
                label="First Name"
                variant="standard" />
              <TextField
                className={classes.formInput}
                name="lastName"
                onChange={e => this.handleChange(e.target.value)}
                required
                id=""
                type="text"
                InputLabelProps={{
                  shrink: true,
                }}
                label="Last Name"
                variant="standard" />

And here is the onchange handler

   handleChange = (e) => {
     this.setState({
       [e.target.name]: e.target.value
     });
   }

CodePudding user response:

Most likely that you want to add this validation only after user trying to submit the form. Then, you should create a new state for formError and add it to your submit function condition which will check that if your inputs are empty then set state of formError to true. After that, your expression for input error state will look like:

error={formError && firstName.length === 0}

You will get a nice user experience when your inputs will be highlighted with red only when there was an attempt to submit a form with empty inputs.

CodePudding user response:

When the user is submitting the form, since all you want to do is validate that something is filled into the firstName and lastName fields, you can check this with either:

this.state.field !== '' //returns true if it's filled in

or

this.state.field.length > 0 //returns true if it's filled in

in whatever 'handleSubmit' function you create, you can call a seperate function to validate all your fields. That validating function can look like this:

// returns 'true' if fields filled out, and 'false' if not 
validateForm = () => {
  if (this.state.firstName === '' || this.state.lastName === '') {
    //set error message: 'Please fill out all fields')
    return false;
  } else {
    return true;
  }
}
  • Related