Snedden27
Snedden27

Reputation: 1930

Validate time in format as" hh:mm:ss am/pm " in javascript

Can anyone tell me how to validate time (which is an html input element) in the format as hh:mm:ss AM/PM in javascript

Upvotes: 1

Views: 4196

Answers (2)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201588

The simplest way is probably to use globalize.js, which lets you test simply for

Globalize.parseDate(data, 'T')

for not being null, e.g. if(Globalize.parseDate(data, 'T')) .... This particular variant requires the exact format you exemplified, with seconds and am/pm indicator always included, though case-insensitively for the am or pm designator. You can use other formats instead of T to specify different parsing.

An additional beauty of this approach is that this piece of your code will be globalization-ready. Just setting a variable identifying the locale, you can make the code parse by the rules of different languages (for “long time” notations, in this case). Check out some code samples that illustrate the possibilities.

Upvotes: -1

sg3s
sg3s

Reputation: 9567

There are probably better regexes out there but lets do something basic.

Get the input and attach an event on blur (will not explain how to do this; search for 'attach event to dom element in javascript' or something alike)

In that even you can do something like this:

if(/(?:[0-1]?[0-9]|[2][1-4]):[0-5]?[0-9]:[0-5]?[0-9]\s?(?:am|pm)?/.test(this.value)) {
    // Validates
} else {
    // Something is wrong
}

For better regexes to test time formats, or other formats, search for 'validate time regex javascript' or something similar (there are tons out there).

This particular regex validates time, you can play arround with it here if you want:

http://rubular.com/r/cYs1n3UuKO

Bear in mind that ruby and javascript regexes do differ slightly, but for something as simple as this you can use rubular which has a good interface for easy testing.

Upvotes: 2

Related Questions