How to invalidate a TextField in Material UI

Viewed 107867

I am using TextField component to capture phone number. As the user is typing, I want to invalidate the entry if it is not a number or if it does not follow a format and display the errorText. Currently errorText is displayed even without touching the field. How can I achieve this behavior?

Any help is greatly appreciated.

4 Answers

As of 0.20.1 you can helperText and error props

<TextField 
    hintText="Phone"
    error ={this.state.errorText.length === 0 ? false : true }
    floatingLabelText="Phone"
    name="phone"
    helperText={this.state.errorText}
    onChange={this.onChange.bind(this)}/>

Material-UI v3.9.3 working version:

class UserProfile extends React.Component {
  constructor(props) {
    super(props);
    this.state = { helperText: '', error: false };
  }

  onChange(event) {
    if (event.target.value.length > 2) {
      this.setState({ helperText: '', error: false });
    } else {
      this.setState({ helperText: 'Invalid format', error: true });
    }
  }

  render() {
    return (

                   <TextField
                      helperText={this.state.helperText}
                      onChange={this.onChange.bind(this)}
                      error={this.state.error}
                      required
                      id="outlined-required"
                      label="First Name"
                    />
                     );
  }
Related