0

I am trying to check if the user input contains only 0 or 1 with Regex? But It also accepts different values.

inputChange = (e) => {
    console.log(/(^$)|[0,1]*/g.test(e.target.value));
};

The method above returns true for a string '222' but when I use online Regex checker it says that my Regex is correct.

fiza khan
  • 1,240
  • 12
  • 24
Zotov
  • 255
  • 1
  • 7
  • 19

1 Answers1

1

Why it is matching other values too ?

Well [0,1]* here * means match zero or more time so in case of values other than 0 and 1 it still matches but zero time

So you can change * to +

/(?:^$)|^[01]+$/
    |     |__________  Matches string with only zero and one
    |     
    |________________  Match empty strings. ( Non capturing group)

console.log(/(?:^$)|^[01]+$/.test('222'))
console.log(/(?:^$)|^[01]+$/.test(''))
console.log(/(?:^$)|^[01]+$/.test('1111111 111111'))  // fails because there's a space
console.log(/(?:^$)|^[01]+$/.test('010101'))

On side note:- You should not use g flag with test. read here why-does-a-regexp-with-global-flag-give-wrong-results

Code Maniac
  • 35,187
  • 4
  • 31
  • 54