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.
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
})
}
};