1
function validateFor9DigitNumber() {  var txt = document.getElementById('<%= txt9Digit.ClientId %>');  var textValue = parseInt(txt.value);  var regSSN1 = new RegExp("^\d{9}$");  if (isNaN(textValue))      alert("Not a Number");  else {      alert("A Number");      alert(regSSN1.test(textValue));  }}

I needed a Javascript function that would pattern match a text value for 9-digit number.

In the above needed function, I do land up in the else part and get the message"A Number", but then receive aFALSE for the next validation.

When I enter a 9-digit number say 123456789. I get FALSE even withegSSN1.match(textValue).

Where am I going wrong?

askedMar 24, 2011 at 1:34
CocaCola's user avatar

2 Answers2

3
var regSSN1 = new RegExp("^\\d{9}$");

(Note the double backslash)

When using a literal string for a regex, you have to double-backslash.

You can also do:

var regSSN1 = /^\d{9}$/;

To avoid that problem.

answeredMar 24, 2011 at 1:39
Brian Roach's user avatar
Sign up to request clarification or add additional context in comments.

Comments

1

Avoid escaping issues in regular expression strings by using a regular expression literal:

/^\d{9}$/.test("123456789"); // true

Otherwise:

new RegExp("^\d{9}$").test("123456789"); // false (matches literal backspace)new RegExp("^\\d{9}$").test("123456789"); // true (backslash escaped)
answeredMar 24, 2011 at 1:45
Wayne's user avatar

Comments

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.