Reputation: 35
I'm developing a reactjs application and I want that my user must enter only alphabets in an input field. Here is my code.
<input value= {this.state.val} onChange = {this.handleVal}/>
handleVal = (e)=>{
this.setState({
val:e.target.value
})
}
state = {
val:''
}
My component has lot of code but i entered only the relevant. Thanks in advance.
Upvotes: 1
Views: 3357
Reputation: 73
You can use onKeyPress method it will avoid typing anything else from alphabets.
<input placeholder="Enter Alphabets only" onKeyPress={this.onKeyPress} onChange={this.onChange} />
onKeyPress = (event) => {
if((event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 &&
event.charCode < 123)){
return true;
}
return false;
}
onChange = (e) => {
console.log('_________', e.target.value);
this.setState({
value: e.target.value
})
}
Upvotes: 0
Reputation: 1953
You can use a Regular expression test, and only update the input state if it passes the test on the onChange handler
/^[a-zA-Z]*$/
Usage in your onChange handler
handleVal = (e) => {
const value = e.target.value;
const regMatch = /^[a-zA-Z]*$/.test(value);
if (regMatch) {
this.setState({
val: value
})
}
};
Upvotes: 3