Forum Moderators: coopster

Message Too Old, No Replies

Time Validation Regular Expression

         

benj0323

8:47 pm on Aug 16, 2004 (gmt 0)

10+ Year Member



I can't find a regular expression to validate time in the following formats:

HH:MM AM or PM or am or pm

Can anyone help me out here? I've tried writing my own about 50 times and I cant get it to work, and I can't find any on the internet that work correctly.

Any help is greatl appreciated. Thank you very much.

coopster

11:41 pm on Aug 16, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



What have you got so far?

ergophobe

3:29 pm on Aug 17, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



So it looks like twelve-hour time. How about something like

[01][0-9]:[0-6][0-9]?[aApP]\.?[mM]\.?

coopster

5:44 pm on Aug 19, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Close, ergophobe, but as is, the regular expression would fail as it would return invalid time formats. For example...
19:01 am 
00:69 am
...would be incorrectly accepted. We'll have to expand our pattern to catch that. Below are two similar regular expressions, the only difference being how many spaces must be present between the digits and the "am/pm".

// Must have one and only one space... 
"/(0[1-9]¦1[0-2]):[0-5][0-9] ([ap]m¦[AP]M)/"
// Must have at least one space...
"/(0[1-9]¦1[0-2]):[0-5][0-9]\s+([ap]m¦[AP]M)/"

Don't forget that the vertical pipe "¦" symbol is modified by posting in this forum -- you must replace it with the solid vertical pipe character from your keyboard.

ergophobe

5:51 pm on Aug 19, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



LOL (which is the first time I have *ever* used that acronym). At least I got a chuckle looking at it again.


[01][0-9]:[0-6][0-9]?[aApP]\.?[mM]\.?

The part in italics was a mere oversight; the part in bold was just plain stupidity - sixty minutes, so you need a six right?

coopster

6:03 pm on Aug 19, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



hehe. I did like the optional "dots" between the am/pm though.

To explain it a bit better for benj0323:

If the time format is

01, or 02, or 03...or 09 
OR
10, or 11, or 12
followed by a colon
followed by 00, or 01, or 02...or 59
followed by a space
followed by am or pm or AM or PM
then it's a match.