-3

I'm validating the date format as DD.MM.YYYY using the regex ^(\d{2}).\d{2}.(\d{4})$.

Unfortunately this is not working in the following scenarios.

 02:02:200 -> still gives as valid date even though used  :
 33.33.3333 -> still gives as validate even though there is no 33 date and month etc.

What is the correct regex for DD.MM.YYYY?

klmuralimohan
  • 749
  • 1
  • 12
  • 31
  • Does this answer your question? [Regex to validate date format dd/mm/yyyy](https://stackoverflow.com/questions/15491894/regex-to-validate-date-format-dd-mm-yyyy) – Dams May 18 '20 at 11:13

2 Answers2

2

If you need to check for something, like 31-st of June (non-existent) or 29-th of February in a non-leap year, you would need something more sophisticated than simple RegExp:

const test1 = '02:02:200',
      test2 = '33.33.3333',
      
      validate = dateStr => {
        const [dd, mm, yyyy] = dateStr.split('.'),
              date = new Date(yyyy, +mm-1, dd)
        return  date.getFullYear() == yyyy &&
                date.getMonth() == mm-1 &&
                date.getDate() == dd
      }
      
console.log(test1, validate(test1))
console.log(test2, validate(test2))
console.log('21.06.1982', validate('21.06.1982'))
.as-console-wrapper{min-height:100%;}
Yevgen Gorbunkov
  • 12,646
  • 3
  • 13
  • 31
0

To be able to validate this using a regex you'd have to base the day range on what month it is, and if it's a leap year, or if it was during a time when calendars changed, and some dates were skipped, or added; this depending on locale.

You're better off using some date lib and ask it if the string can be parsed to a proper date.

See this answer for example how to do it with Moment.js https://stackoverflow.com/a/22184830/108804

Ledhund
  • 1,208
  • 12
  • 22
  • I would say, such a simple task is not worth neither building a mind cracking regexp nor attaching some library (for this purpose only) with date parsing feature . [Few simple lines](https://stackoverflow.com/a/61868501/11299053) may do the trick pretty easily. – Yevgen Gorbunkov May 18 '20 at 12:17
  • 1
    I agree! It seems I stopped reading the docs after "It is not recommended to use Date.parse as until ES5..." didn't bother to understand it :) Well, we agree that this isn't a job for regex, which was my main concern. – Ledhund May 19 '20 at 03:53