【问题标题】:Validating time in Dashcode widget在 Dashcode 小部件中验证时间
【发布时间】:2013-09-03 18:11:58
【问题描述】:

我正在尝试验证此输入字段中没有 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;
}

【问题讨论】:

  • 它不会在所有浏览器中都有效,但为什么不使用 HTML5 时间输入类型呢?只需将 type="text" 更改为 type="time",您就已经在大多数浏览器中拥有了客户端验证和时间选择器小部件。您可能还可以通过 github.com/dsheiko/HTML5-Form-Shim 之类的方式在不支持它的旧浏览器上填充支持

标签: javascript macos widget dashboard dashcode


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多