1

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.

2 Answers 2

3

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
        })
    }
  };
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.