-1

I have the following regular expression:

\d{4}(-\d{2}){2}

Which is supposed to match dates that follow the YYYY-MM-DD format, so 1990-01-01 should successfuly match. However this fails when I try it in javascript.

var x = new RegExp('\d{4}(-\d{2}){2}')
x.test('1990-02-01')    //why is this false?
ninesalt
  • 4,054
  • 5
  • 35
  • 75
  • Why not use regex literal syntax? – Pointy Sep 11 '18 at 19:35
  • @pointy what do you mean? – ninesalt Sep 11 '18 at 19:35
  • 1
    this is quite neat on the surface but what if someone enters, say, 2018-02-31? That's not a valid date, but it passes the RegEx. I wouldn't try and validate dates using regexes. You could potentially account for the varying lengths of months with a more complex expression, but realistically you can't account for leap years. One technique is to use a date library which can tell you if a date is actually real or not, momentJS provides such functionality, for example. – ADyson Sep 11 '18 at 19:36
  • `/\d{4}(-\d{2}){2}/` – Pointy Sep 11 '18 at 19:37

1 Answers1

2

Use the regular js regex syntax. Like this:

var x = /\d{4}(-\d{2}){2}/;
console.log(x.test('1990-02-01'));

if you want to keep the new RegExp part, you have to escape the string's backslashes:

var x = new RegExp('\\d{4}(-\\d{2}){2}');
console.log(x.test('1990-02-01'));
Nelson Teixeira
  • 6,297
  • 5
  • 36
  • 73