How to invalidate a TextField in Material UI

Mo3z picture Mo3z · Mar 9, 2016 · Viewed 64k times · Source

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.

Answer

Mo3z picture Mo3z · Mar 15, 2016

Extending Larry answer, set errorText to a property in state (errorText in below example). When the value in TextField changes, validate the entry and set the value of the property (errorText) to display and hide the error.

class PhoneField extends Component
  constructor(props) {
    super(props)
    this.state = { errorText: '', value: props.value }
  }
  onChange(event) {
    if (event.target.value.match(phoneRegex)) {
      this.setState({ errorText: '' })
    } else {
      this.setState({ errorText: 'Invalid format: ###-###-####' })
    }
  }
  render() {
    return (
      <TextField hintText="Phone"
        floatingLabelText="Phone"
        name="phone"
        errorText= {this.state.errorText}
        onChange={this.onChange.bind(this)}
      />
    )
  }
}