Reputation: 25210
I am trying to create a javascript function with regular expression to validate and format the time 24 hours, accepting times without semicolon and removing spaces.
Examples:
If the user types "0100"
, " 100"
or "100 "
it would be accepted but formatted to "01:00"
If the user types "01:00"
it would be accepted, with no need to format.
Thanks.
Upvotes: 6
Views: 23320
Reputation: 5310
function formatTime(time) {
var result = false, m;
var re = /^\s*([01]?\d|2[0-3]):?([0-5]\d)\s*$/;
if ((m = time.match(re))) {
result = (m[1].length === 2 ? "" : "0") + m[1] + ":" + m[2];
}
return result;
}
alert(formatTime(" 1:00"));
alert(formatTime("1:00 "));
alert(formatTime("1:00"));
alert(formatTime("2100"));
alert(formatTime("90:00")); // false
Any call with invalid input format will return false.
Upvotes: 22