javascript - javascript中的正则表达式24小时时间验证

标签 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 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/

相关文章:

javascript - 单击按钮不起作用。我关注了一个 YouTube 视频,但它对我不起作用

Javascript 正则表达式的模式不起作用

javascript - 加载后数据是否有助于网页加载性能?

javascript - ReactJS onClick 未触发

javascript - bxSlider - 将 div 放置在 slider + 文本和背景中

java - 从规范类名解析 Java 包和类名的正则表达式

regex - 如何突出显示没有重复字符串的行?

c++函数将time_t格式化为std::string:缓冲区长度?

php - 根据一天中的时间运行代码

javascript - react native 捆绑无法工作(已完成但未捆绑项目)