I am trying to validate a variable contains a 9-digit number in Javascript. This should be basic but for some reason this is failing:
var test = "123123123";
var pattern = new RegExp("/\d{9}/");
if(test.match(pattern))
{
//This code never executes
}
else
{
//This code is always executing
alert('no match!');
}
Can anyone see why I am not getting a match?
I also tried type-casting test to an integer with:
test = Number(test);
…but this doesn’t work as it has to be a String to support the .match method.
You’re mixing the two different regex constructors. Pick one:
N.B. you probably want to add start and end anchors (as above) to make sure the whole string matches.