I'm trying to write a JavaScript function that would cover the validation of all the input
elements of the type="time"
. I am looking at the documentation of jQuery Validate but I'm only finding examples where the validation is bound on an id
or name
property. Is there a way to do this globally?
I want to make sure that a time is always of the format hh:mm
. I have found a function that will validate my time (see below). When this function returns false
, I would invoke an addError()
function to add an error to the form. I'm not sure how to do this.
// Check is the input is a valid time
function formatTime(time) {
var result = false, m;
var re = /^\s*([01]?\d|2[0-3]):([0-5]\d)\s*$/;
if ((m = time.match(re))) {
result = (m[1].length == 2 ? "" : "0") + m[1] + ":" + m[2];
}
return result;
}
// Trigger the validation on the onBlur event
$("input[type=time]").blur(function () {
var value = formatTime($(this).val());
if (value == false) {
addError($(this));
}
});
Edit1: It seems like my copy/paste skills aren't that good. In formatTime()
I return the time if the format is valid and false
if not.