使用正则表达式验证时间 00:00 的 Javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2048460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:34:16  来源:igfitidea点击:

Javascript function to validate time 00:00 with regular expression

javascriptregexvalidationfunctiontime

提问by Amra

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.

我正在尝试使用正则表达式创建一个 javascript 函数来验证和格式化时间 24 小时,接受没有分号的时间并删除空格。
示例:
如果用户键入"0100"" 100"或者"100 "它会被接受但被格式化为"01:00"
如果用户键入"01:00"它会被接受,而无需格式化。

Thanks.

谢谢。

回答by OcuS

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.

任何输入格式无效的调用都将返回 false。