Answers for "material ui input validation"

1

material ui input validation

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)}
      />
    )
  }
}
Posted by: Guest on March-20-2021

Browse Popular Code Answers by Language