Javascript 在Dashcode小部件中验证时间

Javascript 在Dashcode小部件中验证时间,javascript,macos,widget,dashboard,dashcode,Javascript,Macos,Widget,Dashboard,Dashcode,我正在尝试验证此输入字段中没有am/PM的12小时时间。最好的方法是什么?我已经列出了我目前没有解决的问题。我已经找了几天了,想知道如何处理这个问题 <input id="dtstartf" type="text" name="time" value="08:00" class="apple-textfield apple- no-children" apple-part="com.apple.Dashcode.part.textfield" onkeypress="time(even

我正在尝试验证此输入字段中没有am/PM的12小时时间。最好的方法是什么?我已经列出了我目前没有解决的问题。我已经找了几天了,想知道如何处理这个问题

<input id="dtstartf" type="text" name="time" value="08:00" class="apple-textfield apple-   no-children" apple-part="com.apple.Dashcode.part.textfield" onkeypress="time(event)">

function time(event) {
  var regex = ["[0-2]",
  "[0-4]",
  ":",
  "[0-6]",
  "[0-9]",
  "(A|P)",
  "M"],
  string = $(this).val() + String.fromCharCode(e.which),
  b = true;
  for (var i = 0; i < string.length; i++) {
    if (!new RegExp("^" + regex[i] + "$").test(string[i])) {
        b = false;
    }
  }
  return b;
}

以下函数看起来正常工作:

function validateTime(time) {
    // Check pattern
    var pattern = /^\d{1,2}:\d{1,2}$/;
    if (!pattern.test(time)) {
        return false;
    }
    // Split them and check the individual values
    var splitvalues = time.split(':');
    if (splitvalues[0] > 12 || splitvalues[0] < 1 || splitvalues[1] < 0 || splitvalues[1] > 59) {
        return false;
    }
    // If we get to this point, everything should be valid
    return true;
}

但是,正如您特别提到的,这是针对Dashcode小部件的,我认为HTML5时间输入类型可能就足够了,在这种情况下,将输入类型更改为时间就足够了。

它不会在每个浏览器中都起作用,但为什么不使用HTML5时间输入类型呢?只要将type=text更改为type=time,大多数浏览器中都已经有了客户端验证和时间选择器小部件。您还可以在不支持它的旧浏览器上填充支持,例如