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.

Community
  • 1
  • 1
IrfanClemson
  • 1,699
  • 6
  • 33
  • 52

2 Answers2

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"));
Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97
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}");
dquijada
  • 1,697
  • 3
  • 14
  • 19