Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript中的Regex 24小时时间验证_Javascript_Regex_Time - Fatal编程技术网

javascript中的Regex 24小时时间验证

javascript中的Regex 24小时时间验证,javascript,regex,time,Javascript,Regex,Time,我使用此正则表达式验证时间: var time = document.getElementById("time").value; var isValid = /^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$/.test(time); if (isValid === false) { errors += '- ' + ' Invalid Time Input.\n'; } if (errors) alert('The follow

我使用此正则表达式验证时间:

var time = document.getElementById("time").value;
var isValid = /^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$/.test(time);
if (isValid === false) {
    errors += '- ' + ' Invalid Time Input.\n';
}
if (errors)
    alert('The following error(s) occurred:\n' + errors);
document.MM_returnValue = (errors === '');
虽然这在大多数情况下都有效,但可以接受
9:50
等输入。我需要强制用户在少于10秒的时间内输入前导的
0
。i、 e有效时间应为
09:50
我在这里遗漏了什么?

有两件事:


  • 2[0-4]
    必须是
    2[0-3]
    ,因为没有
    24:59
    时间
  • 似乎您只需要删除
    [0-1]?
    中的
    ,因为
    量词表示1或0个重复
注意:您不需要在此处捕获组,因为您没有使用子匹配。建议将这些组替换为非捕获组,或由于冗余而删除

使用

在代码段中:

var time = document.getElementById("time").value;
var isValid = /^(?:[01][0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9])?$/.test(time);
if (isValid === false) {
    errors += '- ' + ' Invalid Time Input.\n';
}
if (errors)
    alert('The following error(s) occurred:\n' + errors);
document.MM_returnValue = (errors === '');

/^([0-1]?[0-9]| 2[0-4]):([0-5][0-9])(:[0-5][0-9])?$/
中,第一个
表示
0-1
可能出现或不出现,只需将其删除,然后强制0或1出现
2[0-4]
必须是
2[0-3]
。没有
24:59
时间。另外,您似乎只需要删除
[0-1]、
/^([01][0-9]| 2[0-3]):([0-5][0-9])(:[0-5][0-9])?$/
中的
。根本不确定你是否需要捕获组,
/^(?[01][0-9]| 2[0-3]):[0-5][0-9](?:[0-5][0-9])?$/
应该可以。哇,这实际上非常有用。这起作用了。非常感谢。
var time = document.getElementById("time").value;
var isValid = /^(?:[01][0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9])?$/.test(time);
if (isValid === false) {
    errors += '- ' + ' Invalid Time Input.\n';
}
if (errors)
    alert('The following error(s) occurred:\n' + errors);
document.MM_returnValue = (errors === '');