Take the 2-minute tour ×

I am using ASP.Net MVC to validate that a string will not contain more than 2 numbers in any form.

I'm using the following server side code:

[RegularExpression(@"[^\d]*\d?[^\d]*\d?[^\d]*",ErrorMessage = "More than 2 Numbers are not allowed")]

That works great, but the following JavaScript code will always return 0:

>> var mystring = "test123"; 
>> var myregax = new RegExp("[^\d]*\d?[^\d]*\d?[^\d]*"); 
>> mystring.search(myregax); 
>> mystring = "test"; 
>> mystring.search(myregax); 

What am I missing and what is the difference between the regular expression syntax of ASP.Net and JavaScript?

share|improve this question

3 Answers 3

up vote 3 down vote accepted

Using RegExp object you have to escape the \ in your pattern

new RegExp("[^\\d]*\\d?[^\\d]*\\d?[^\\d]*"); 

or, as alternative, use this syntax

var myregax = /[^\d]*\d?[^\d]*\d?[^\d]*/;
share|improve this answer
+1 for suggesting the better alternative syntax. –  jbabey Sep 27 '12 at 12:29
for some reason that is still not working (will always return 0) any idea why? –  python Sep 27 '12 at 12:44
use myregax.test("test123"); or provide a jsfiddle/jsbin example –  Fabrizio Calderan Sep 27 '12 at 12:47
ok thanks for the kind help jsbin.com/eqirif/3/edit –  python Sep 27 '12 at 13:15

In addition to Fabrizio Calderan's answer, which is entirely correct, you are using search().

search() returns the starting index of the first match, which is 0 since the entire string matches the regex. You should be calling test() instead, which returns a boolean if the regex matches or not.

Edit: a regex like this:


Would return true for anything that has two or more numbers, so your condition would be:

if (/\D*\d{1}\D*\d{1}\D*/.test(string)) {
    // 2 or more numbers, validation failed
} else {
    // less than 2 numbers, validation passed
share|improve this answer
then i guess something is worng with my expresstion becuase it still always return true:var myregax = /[^\d]*\d?[^\d]*\d?[^\d]*/; >> myregax.test("test123"); –  python Sep 27 '12 at 12:59
@python yes, your regex matches anything, what are you trying to accomplish? regexr.com?329po –  jbabey Sep 27 '12 at 13:18
to allow only 2 numbers in the string (no matter in what format), but the funny thing is that on server side with the RegularExpression attribute it works perfectly so why on js it doesn't? –  python Sep 27 '12 at 13:47
@python see my edit - i think your condition is just backwards. –  jbabey Sep 27 '12 at 13:54
it simply works, big thanks for all the proccess :) will upvote now –  python Sep 27 '12 at 14:24
var mystring = "test123";
if(filter.test(mystring)) {
} else {
share|improve this answer

Your Answer


