-2

I'm trying to filter out date results, but I think I may have the regular expression wrong.

if ((strSearchInx == 6) || (strSearchInx == 7)) {
       var regDate = new RegExp("/^\d{1,2}\/\d{1,2}\/\d{4}$/");
       strSearchField = strSearchField.trim();
       //alert(strSearchField);
       if (regDate.test(strSearchField) == false) {
          alert("Date does not match mm/dd/yyyy format. Please re-enter");
          document.getElementById('searchfield').focus();
          return false;
       }

     }

I've tested it against 8/3/2016 and it doesn't seem to let any response through: Is /^\d{1,2}/\d{1,2}/\d{4}$/ the correct regular expression?

Thanks.

John Meyer
  • 37
  • 1
  • 8
  • seems to work https://regex101.com/r/uN2sH3/1 . are you sure the input is correct? – Pabs123 Aug 04 '16 at 15:30
  • 1
    Use regex literal syntax `/^\d{1,2}\/\d{1,2}\/\d{4}$/` OR `new RegExp("^\\d{1,2}\/\\d{1,2}\/\\d{4}$")` – Tushar Aug 04 '16 at 15:30
  • Are you testing this regex to the exact string "8/3/2016" , or to a string containing that date? – Joachim VR Aug 04 '16 at 15:30
  • Should do what you expect so perhaps strSearchInx is not 6/7 chars long – Alex K. Aug 04 '16 at 15:30
  • Don't forget to change your error message, since m/d/yyyy, mm/d/yyyy and m/dd/yyyy seem to be allowed as well – Mateo Barahona Aug 04 '16 at 15:33
  • @Tushar : `new RegExp("^\\d{1,2}\/\\d{1,2}\/\\d{4}$")` without / at start and end – Mateo Barahona Aug 04 '16 at 15:34
  • Tried putting it in literally: `var regDate = new RegExp("/^\d{1,2}\/\d{1,2}\/\d{4}$/"); strSearchField = strSearchField.trim(); //alert(strSearchField); if (regDate.test("8/3/2016") == false) { alert("Date does not match mm/dd/yyyy format. Please re-enter"); document.getElementById('searchfield').focus(); return false; }` Still does not let it go through. – John Meyer Aug 04 '16 at 15:35
  • @JohnMeyer Use the literal format. When using the `RegExp` constructor the backslashes need to be escaped. – Tushar Aug 04 '16 at 15:35

1 Answers1

1

You're not using Regexp object correctly. You should do :

var regDate = new RegExp("^\\d{1,2}\/\\d{1,2}\/\\d{4}$");

See how \d is escaped, and you should not start and end your regexp with /, it's used to start and end literal regexp, not regexp wrapped in an object.

Mateo Barahona
  • 1,381
  • 8
  • 11