Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
33
rated 0 times [  37] [ 4]  / answers: 1 / hits: 118688  / 8 Years ago, wed, march 9, 2016, 12:00:00

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.


More From » validation

 Answers
19

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)}
/>
)
}
}

Updated based on comment below that errorText is replaced by helperText


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"
helperText= {this.state.errorText}
onChange={this.onChange.bind(this)}
/>
)
}
}

[#63001] Monday, March 7, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zane

Total Points: 471
Total Questions: 94
Total Answers: 91

Location: Bahrain
Member since Sun, Mar 27, 2022
2 Years ago
;