0

I'm trying to check if the input value either matches the date format YYYY-MM-DD or YYYY-MM-DD - YYYY-MM-DD using the following code, but it returns false on the input 2018-01-29.

  const singleDateRegex = new RegExp('\d{4}-\d{2}-\d{2}$');
  const rangeRegex = new RegExp('\d{4}-\d{2}-\d{2} \d{4}-\d{2}-\d{2}$');

  const matchSingle = singleDateRegex.test(value); //false
  const matchRange = rangeRegex.test(value);       //false
matchifang
  • 5,190
  • 12
  • 47
  • 76

1 Answers1

1

You have to escape \ (\\) used in the RegExp constructor.

Why don't use a regular expression literal, which consists of a pattern enclosed between slashes:

const singleDateRegex = new RegExp(/\d{4}-\d{2}-\d{2}$/);
const rangeRegex = new RegExp(/\d{4}-\d{2}-\d{2}\s\d{4}-\d{2}-\d{2}$/);

console.log(singleDateRegex.test('2018-01-29'));
console.log(rangeRegex.test('2018-01-29 2018-01-29'));
Mamun
  • 66,969
  • 9
  • 47
  • 59