简体   繁体   中英

Javascript function to validate time 00:00 with regular expression

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.

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM