我使用这个正则表达式来验证时间:
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 === '');
关于javascript - javascript中的正则表达式24小时时间验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55296891/