Reputation: 672
I'm developing app in React native and would like to allow user to type into input only letters or only numbers, so if first character is letter then user wouldn't be able to type any number after that, and opposity if first character is number then user wont be able to type any letter after that. Actually have no idea how to even start it, I guess best would be probably to check first character with regex and then based on this disable typing letters/numbers but not sure how to do so.
(/[a-zA-Z]/).test(this.state.myValue.charAt(0)) ? "disable typing numbers" : "disable typing letters"
my TextInput looks like this:
<TextInput
onChangeText={e=> this.handleInput(e), "myValue"}
value={this.state.myValue}
/>
handleInput(value, key) {
/^(?:[A-Za-z]+|\d+)$/.test(value) ? "block number" : "block letter"
this.setState({[key]: value)}
}
Upvotes: 2
Views: 14083
Reputation: 627468
You may use
/^(?:[A-Za-z]+|\d+)$/.test(this.state.myValue)
Details
^
- start of string(?:
- start of a "container" non-capturing group:
[A-Za-z]+
- 1+ letters|
- or \d+
- 1+ digits)
- end of the group$
- end of string.See the regex demo and the regex graph:
Upvotes: 10