Home > Software engineering >  I want to add a Regex validation in React to accept only number and decimalupto two place for ex : 1
I want to add a Regex validation in React to accept only number and decimalupto two place for ex : 1

Time:06-09

here is my below code in react which is accepting 0-9 values only the values i need to be accepted are 1 11 11.1 11.11 111.1 111.11

like so    const handleKeyPress = (event) => {
        if (!/[0-9]/.test(event.key)) {
            event.preventDefault();
            alert('Please enter a valid amount')
        }
    }

CodePudding user response:

I'm assuming that this is in the context of an <input> field or something like that.

When you look at @Andrew Allison's regular expression you will see that it reads /^\d .... as in "needs to start with a number". When you test any of your examples against this expression you will see that the expression is correct.

The problem is the context, i.e. event.key. You are testing a single key here, but . or , don't start with a number. You either need to test against the value of the field: .test(event.target.value) or use a different expression, i.e. (\d|\.|,). The problem with the latter approach is that ..., ,,1.., etc. would also be valid, which presumably is not what you want.

CodePudding user response:

const handleKeyPress = (event) => {
  if (!/^\d (?:[.,]\d{1,2})?$/.test(event.key)) {
    event.preventDefault();
    alert('Please enter a valid amount')
  }
}

Although I'm almost certain this question has already been asked on StackOverflow. You need to search for it next time.

  • Related