0

I want user to type either 7 digits number or 10 digits number in a textbox.

My code:

var numberfilter = /^([0-9]{7})|([0-9]{10})$/;
var x=document.forms["myForm"]["number_field"].value;
if(numberfilter.test(x)==true)
    alert("Valid");
else if(numberfilter.test(x)==false)
    alert("Invalid");

The above regular expression is showing "valid" for 7 or more digits also. Please help!

Learner AKS
  • 183
  • 1
  • 2
  • 10

4 Answers4

3

The | operator applies to the whole expressions on the left and right side not just the group in brackets, unless you put it inside a group. So your expression is basically:

^([0-9]{7}) or ([0-9]{10})$

what you need is duplicate the ^$ anchors on both sides of |:

^([0-9]{7})$|(^[0-9]{10})$

or

group the whole thing apart from anchors:

^(([0-9]{7})|([0-9]{10}))$

EDIT: The above explains where you went wrong, but the solution is not the best one. See the reference in comment for the slicker solution:

^(\d{7})(\d{3})?$

K. Kirsz
  • 1,384
  • 10
  • 11
0

DEMO

var numberfilter = /^\d{7}(?:\d{3})?$/;
var x='6666666666';
var y='66666666';
var z='6666666';
test(x);
test(y);
test(z);
function test(x){
 if(numberfilter.test(x)==true)
    console.log(x+" Valid");
 else if(numberfilter.test(x)==false)
    console.log(x+" Invalid");
}

Here is Regex /^\d{7}(?:\d{3})?$/ checks for first 7 digit with (?: capturing group for next 3 digit

Durga
  • 15,263
  • 2
  • 28
  • 52
0

try regex

/^([0-9]{7})$|^([0-9]{10})$/ (whole word length is 7 or whole word length is 10)

Azad
  • 5,144
  • 4
  • 28
  • 56
0

Your regex actually says "Match if the first 7 characters are numbers OR if the last 10 characters are numbers".

This is because you forgot to place the anchors on both ends of the conditionals. Try something like this.

^([0-9]{7})$|^([0-9]{10})$

You can see it work here.

Jeremy Myers
  • 159
  • 6