1

Is there a way to block a specific character and only allow string from a - z in react? what I want is the user can only input a-z, and block others like [@,.-_] or even ' '(space).

2 Answers 2

2
onChange={(e) => {
  let val = e.target.value

  val = val.replace(/[^A-Za-z]/ig, '')

  this.setState({
    value: val,
  })
}}
Sign up to request clarification or add additional context in comments.

1 Comment

it should be onChange= (e) => { let val = e.target.value val = val.replace(/[^A-Za-z]/ig, '') this.setState({ inputValue: val, }) }
0

We can use regx for filtering only alphanumeric values.

onChangeAlphaNumericInput(e) {
  const value = e.target.value;
  const regex = /[^A-Za-z]/ig; //this will admit letters, numbers and dashes
  if (value.match(regex) || value === "") {
    this.setState({ inputValue: value });
  }
}

1 Comment

but, it still allows '-'

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.