-1

I have the following regex named 'pattern' that I am testing to try to restrict an input to only numbers. Why are both pattern.test("a") and pattern.test("1") returning true?

const pattern = /^[a-zA-Z0-9]*$/;
if (!pattern.test(event.target.value)) {
    event.target.value = event.target.value.replace(/[^a-zA-Z0-9]/g, "");
}
noclist
  • 1,368
  • 1
  • 18
  • 46

1 Answers1

2

Your expressions /^[a-zA-Z0-9]*$/ matches character ranges a-z, A-Z, 0-9. This will match any alphanumeric character. Adding the * means any number of times including zero. Meaning an empty string will also match.

If you want to match numeric and empty string only use /^[0-9]*$/.

If you want to match numeric only use /^[0-9]+$/.

Brenden
  • 1,545
  • 10
  • 9