-1

I am not experienced in Regular Expression in JavaScript. Could I have a Regular Expression for a date? It should be in the format "mm/dd/yyyy hh:mm AM/PM". Also, each month can only accept 28/30/31 days. If the year is a leap year (year is divisible by 4), then 2/29 could be accepted.

mathenthusiast8203
  • 755
  • 1
  • 7
  • 14
  • 1
    This seems like a [duplicate](http://stackoverflow.com/questions/12717638/need-to-validate-mm-dd-yyyy-hhmm-tt-in-javascript?rq=1). Is there something the other question and answer don't provide that you need? – Shaz May 19 '15 at 19:49
  • You can use this for the bulk of your issue -- http://stackoverflow.com/questions/8647893/regular-expression-leap-years-and-more -- Unless this is for a homework assignment or academic curiosity, consider using `moment.js` – Michael Hays May 19 '15 at 19:57

2 Answers2

3

Though it could probably be done with a regex, it would become complicated and unreadable, and I personally don't think that it would be the best solution here. A leap year is more complex than 'is divisible by 4' for instance. 1900 was no leap year, and neither will 2100...

I would work with my favorite date js toolbox in your case, moment.js

The code would look something like this:

moment(myDate, 'M/D/YYYY h:mm a').isValid();

Note that moment.js provides a ton of other, very useful functions. You could for instance cast your date to a timestamp before sending it to your backend, or even perform calculations with your dates if that would be desired. Just have a look at the docs, I promise you you'll love this toolbox!

Pevara
  • 14,242
  • 1
  • 34
  • 47
  • Just to clarify (and lend some support to your argument that leap years are too complicated to handle in regular expressions): 2000 actually _was_ a leap year. The rule is that years evenly divisible by 4 are leap years, _except_ that they are not leap years when they are evenly divisible by 100, _except_ that they remain leap years if they are evenly divisible by 400. Since 2000 is evenly divisible by 400, it _was_ a leap year -- but 1900 wasn't, and 2100 won't be. – Joe DeRose May 19 '15 at 20:04
  • @JoeDeRose you are absolutely right, my mistake. My point remains valid though, as you probably agree. Will update my answer! – Pevara May 19 '15 at 20:08
-1
/[0-1]\d\/[0-3]\d\/\d{4} [0-1]\d:[0-5]\d [aApP][mM]/
lem2802
  • 1,152
  • 7
  • 18