Javascript function to check time 00:00 with regex

I am trying to create a regular expression javascript function to check and format the time of 24 hours, accept time without a semicolon and remove spaces.
Examples:
If the user dials "0100" , " 100" or "100 " , he will be accepted, but formatted at "01:00"
If the user dials "01:00" , he will be accepted, without the need for formatting.

Thanks.

+6
javascript function regex validation time
source share
1 answer

 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 an invalid input format returns false.

+21
source share

All Articles