Form validation with react and material-ui

Solution 1:

Does the check have to happen after a certain delay? A solution that I think would suffice in most situations would be to split your code up a bit. Don't trigger your isDisabled() function in changedValue(). Instead have it run on the onBlur event instead.

Try this:

<TextField
  hintText="Password"
  floatingLabelText="Password"
  type="password"
  errorText={this.state.password_error_text}
  onChange={e => this.changeValue(e, 'password')}
  onBlur={this.isDisabled} 
/>

and then your function becomes:

changeValue(e, type) {
    const value = e.target.value;
    const nextState = {};
    nextState[type] = value;
    this.setState(nextState);
}

Solution 2:

Current Material-UI version doesn't use the errorText prop but there is still a way that you can use to display error and apply validation to the TextField in Material-UI.

We use the error(Boolean) property to denote if there is an error or not. Further to display the error text use helperText property of the TextField in the Material-UI, just provide it the error text you want to display.

Do it like:

<TextField
  value={this.state.text}
  onChange={event => this.setState({ text: event.target.value })}
  error={text === ""}
  helperText={text === "" ? 'Empty!' : ' '}
/>

Solution 3:

Simplest is to call form.reportValidity(). form can be obtained by calling event.currentTarget.form.

Solution 4:

This library that I had created, takes care of everything related to validating fields and it supports material-ui components as well...

To validate your fields, you just need to wrap you field component and you are done... saving a lot of effort in managing state yourself manually.

<Validation group="myGroup1"
    validators={[
            {
             validator: (val) => !validator.isEmpty(val),
             errorMessage: "Cannot be left empty"
            }, ...
        }]}>
            <TextField value={this.state.value}
                       className={styles.inputStyles}
                       style={{width: "100%"}}
                       onChange={
                        (evt)=>{
                          console.log("you have typed: ", evt.target.value);
                        }


     }/>