在Dashcode小部件中验证时间

时间:2013-08-30 23:01:20

标签: 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(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;
}

1 个答案:

答案 0 :(得分:0)

以下功能看起来可以正常工作:

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时间输入类型可能就足够了,在这种情况下只需将输入类型更改为“time”即可。