Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  4] [ 2]  / answers: 1 / hits: 19672  / 10 Years ago, sun, march 30, 2014, 12:00:00

I need to validate an account number.
A valid number could be either a sequence of exactly 11 digits or 3 groups of digits separated by hyphens (2 digits - 3 digits - 6 digits)



I tried this :



/^([0-9]{11})|([0-9]{2}-[0-9]{3}-[0-9]{6})$/


But it only works for the second rule . The first rule doesn't work as it allows numbers of more than 11 digits



This is how I use the regex in my js function :



 var re = /^([0-9]{11})|([0-9]{2}-[0-9]{3}-[0-9]{6})$/;
if (re.test(txtNumber.value)==true) {
return 1;
}
else {
alert(Invalid Account Number);
return 0;
}


Any advise or guidance would be greatly appreciated



VALID NUMBERS:



12345678912 (11 digits)



12-345-678912 (11 digits separated by hyphens)



INVALID NUMBERS:



1223 (less than 11 digits)



111111111111 ( more than 11 digits)



123-23-678912 (11 digits , but not separated correctly, it should be 2 digits-3 digits-6 digits)


More From » regex

 Answers
44

As | regex operator precedence is the lowest, it should be written like this:



/^(?:[0-9]{11}|[0-9]{2}-[0-9]{3}-[0-9]{6})$/


... so that alternation pattern is bound both to the beginning and the end of the string.



As it stands in your code, pattern checks for either sequence of 11 digits at the beginning of the string, or sequence of 'two digits, hyphen, three digits, hyphen, six digits' at its end - but never really bind the rule to both ends. And that's easy to prove:



var patt = /^([0-9]{11})|([0-9]{2}-[0-9]{3}-[0-9]{6})$/;
patt.test('acdbdfdsfsf22-333-666666'); // true


As a sidenote, as you don't need to capture anything with that grouping expression, I've prepended it with ?:. Actually, it can be optimized even more:



/^[0-9]{2}(?:[0-9]{9}|-[0-9]{3}-[0-9]{6})$/


... as the less you alternate, the better. But in this case it really won't matter much, I suppose.






In short, the problem can be illustrated with these two patterns:



/^a|b$/


This reads as 'match either a at the beginning of the string, or b at its end.



/^(?:a|b)$/


This reads as 'match the beginning of the string, followed by either a or b, followed by the end of the string'.


[#71701] Friday, March 28, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
richardaydenc

Total Points: 148
Total Questions: 125
Total Answers: 98

Location: Seychelles
Member since Mon, Jun 28, 2021
3 Years ago
richardaydenc questions
Fri, Dec 4, 20, 00:00, 4 Years ago
Thu, Jul 2, 20, 00:00, 4 Years ago
;