NoushadM
NoushadM

Reputation: 121

How to restrict user from entering numbers or special characters in to text input field in react class components

im trying to restric user from entering numbers using regex in to my text type input . how can i achieve it ,

  nameChangeHandler=(e)=>{
    const userInput={...this.state.userInput};
    const reg=/[0-9]/;
    if(reg.test(e.currentTarget.value))
    e.preventDefault();
    userInput[e.currentTarget.name]=e.currentTarget.value
    this.setState({
      userInput
    })
  }
 <input id="nameInput"  type="text" name="username" value={username} onChange={this.nameChangeHandler} />

This is what i have tried doing

Upvotes: 2

Views: 5322

Answers (1)

grenzbotin
grenzbotin

Reputation: 2565

The regex pattern to "not allow" for numbers (= check whether numbers are not in the string): /^([^0-9]*)$/

Example regex to additionally check for special characters ($ and %): /^([^0-9$%]*)$/

Assuming your current handler works, this should prevent users from typing a number and % and $:

nameChangeHandler=(e)=>{
    const reg=/^([^0-9$%]*)$/;
    if (reg.test(e.currentTarget.value)) {
      this.setState({ ...this.state.userInput, username: e.currentTarget.value })
    }
  }

Upvotes: 2

Related Questions