Javascript函数使用正则表达式验证时间00:00 [英] Javascript function to validate time 00:00 with regular expression

查看:857
本文介绍了Javascript函数使用正则表达式验证时间00:00的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用正则表达式创建一个javascript函数来验证并格式化24小时时间,接受没有分号和去除空格的时间。

例子:

如果用户类型0100100100它会被接受,但格式为01:00

如果用户键入01:00 code>它会被接受,而不需要格式化。



谢谢。

解决方案

函数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] alert(formatTime(1:00)); alert(formatTime(1:00)); alert(formatTime(1:00)); alert(formatTime(2100)) ;警报(formatTime( 90:00)); // false



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

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.

这篇关于Javascript函数使用正则表达式验证时间00:00的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆