简体   繁体   中英

Validating time in Dashcode widget

I am trying to validate 12 hour time without AM/PM in this input field. What is the best way to approach this? I have listed what I have currently which is not working out. Been looking for a couple days on how to approach this to no luck.

<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;
}

The following function looks to work OK:

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;
}

However, as you've specifically mentioned that this is for a Dashcode widget, I think the HTML5 time input type may be sufficient, in which case just changing the input type to "time" will be sufficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM