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