0

I Want to form check text like : YYYY-MM-DD hh:mm (Date time) And I found this ↓

                    "regex": /^((((19|[2-9]\d)\d{2})[\/\.-](0[13578]|1[02])[\/\.-](0[1-9]|[12]\d|3[01])\s(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]))|(((19|[2-9]\d)\d{2})[\/\.-](0[13456789]|1[012])[\/\.-](0[1-9]|[12]\d|30)\s(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]))|(((19|[2-9]\d)\d{2})[\/\.-](02)[\/\.-](0[1-9]|1\d|2[0-8])\s(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))[\/\.-](02)[\/\.-](29)\s(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])))$/,

It worked. but this id checked : YYYY-MM-DD hh:mm:ss And cut :ss part (I think)

"regex": /^((((19|[2-9]\d)\d{2})[\/\.-](0[13578]|1[02])[\/\.-](0[1-9]|[12]\d|3[01])\s(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]))|(((19|[2-9]\d)\d{2})[\/\.-](0[13456789]|1[012])[\/\.-](0[1-9]|[12]\d|30)\s(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]))|(((19|[2-9]\d)\d{2})[\/\.-](02)[\/\.-](0[1-9]|1\d|2[0-8])\s(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))[\/\.-](02)[\/\.-](29)\s(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])))$/,

It doesn't worked. how can i fix this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
user3273401
  • 35
  • 1
  • 10

2 Answers2

3

If you want to check if a string is a valid time, a better approach is to use Date.parse().

Like so:

alert(Date.parse("2001-12-20 20:39"));  // returns 1008841140000
alert(Date.parse("2001-12-50 20:39"));  // returns NaN (sometimes?)

If you want to make extra certain the date matches that format, you can output it and check it against the original, like so:

Date.parse(y).strftime("%Y-%m-%d %H:%M") == y
  • I want to real-time check HTML text form . but Thank you for your answer, I try Date.parse() another function. – user3273401 Oct 15 '14 at 04:48
  • "Better" than what? That format returns `NaN` in Safari, Firefox and a few versions of IE still in use at least. Parsing strings using *Date.parse* (or the Date constructor, which is effectively the same thing) is infamously unreliable, just don't do it. To validate a date using a Date object, see [*How to validate a date?*](http://stackoverflow.com/questions/5812220/how-to-validate-a-date). – RobG Oct 15 '14 at 05:16
1

If you have to use a regular expression, this should work:

/^[0-9]{4}-[0-9]{2}-[0-9]{2}\s[0-9]{2}:[0-9]{2}/

It has no limit on range, so someone could put 14 as the month. It only checks that the format you want is exactly followed with any numbers.

Martin
  • 171
  • 1
  • 8