0

This should be easy. I have the following code:

var patt = new RegExp("\d{3}[\-]\d{1}");
var res = patt.test(myelink_account_val);
if(!res){
  alert("Inputs must begin with something like XXX-X of numbers and a dash!");
  return;
}

Basically, forcing users to enter something like 101-4 . The code is borrowed from Social Security Number input validation . And I can confirm that my inputs are indeed like 101-4; only the first five characters need to fit the pattern.

But running my code always gives the alert--the condition is never matched.

Must be something simple?!

Thanks.

6
  • 2
    Use var patt = /^\d{3}-\d$/ if the whole input should match the pattern. If it should only start with it, use var patt = /^\d{3}-\d/ Commented Feb 16, 2017 at 14:09
  • 5
    If you create a regexp using a string then you need to escape the \ so you have to write \\d Commented Feb 16, 2017 at 14:11
  • /^\d{3}-\d{1}$/ .... um basically what he wrote Commented Feb 16, 2017 at 14:12
  • @t.niese solution works--by escaping with another \ . Thanks.! Commented Feb 16, 2017 at 14:14
  • Possible duplicate of Why do regex constructors need to be double escaped? Commented Feb 16, 2017 at 14:16

2 Answers 2

1

When you use "new RegExp" you are passing it a string.

Two solutions here:

1) Don't use "new RegExp()", but a regexp pattern:

var patt = /\d{3}[\-]\d{1}/

2) If you want to use it, remember you will have to escape the escapes:

var patt = new RegExp("\\d{3}[\\-]\\d{1}");

Also, remember, if a '-' is the only symbol (or first, or last) on a [], you can skip the escape:

var patt = new RegExp("\\d{3}[-]\\d{1}");
Sign up to request clarification or add additional context in comments.

Comments

1

var patt = new RegExp("^\\d{3}[\\-]\\d{1}");
console.log(patt.test("123-4"));
console.log(patt.test("123-456"));
console.log(patt.test("12-4"));
console.log(patt.test("abc-d"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy 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.