views:

197

answers:

1

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.

+5  A: 
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.

OcuS
I fixed it for "27:00" to be invalid.
OcuS
Ah, you beat me to it.
Tim Down
Thanks Ocus, this function does the job.
Cesar Lopez
Thanks Ocus, this function does the prefect job for what I need.
Cesar Lopez