【问题标题】:Regex 24 hours time validation in javascriptjavascript中的正则表达式24小时时间验证
【发布时间】:2019-03-22 09:48:18
【问题描述】:

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

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]?/^([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])?$/ 应该没问题。
  • 哇,这实际上很有帮助。这行得通。谢谢。

标签: javascript regex time


【解决方案1】:

有两件事:

  • 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

在你的代码 sn-p:

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

【讨论】:

    【解决方案2】:

    /^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$/中,第一个?表示0-1可能出现也可能不出现,只要去掉就强制出现0或1

    【讨论】:

      猜你喜欢
      • 2017-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多