Validating time in Dashcode widget

59 views Asked by At

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

There are 1 answers

0
Matthew Daly On

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.