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

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,即有效时间应为09:50我在这里错过了什么?

最佳答案

有两件事:


2[0-4]必须为2[0-3],因为没有24:59时间。
似乎您所需要的只是删除?中的[0-1]?,因为?量词表示1或0个重复。


请注意,由于您没有使用子匹配项,因此此处不需要捕获组。建议将这些组替换为不捕获的组,或者由于冗余而删除。

采用

/^(?:[01][0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9])?$/


请参见regex demo

在您的代码段中:

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 === '');

10-06 13:52
查看更多