I am trying to use the jQuery Mask Plugin by Igor Escobar for time validation:
$("input").mask("Hh:Mm",{
translation: {
'H': { pattern: /[0-2]/ },
'h': { pattern: /[0-9]/ },
'M': { pattern: /[0-5]/ },
'm': { pattern: /[0-9]/ }
}
});
In this solution it is possible to input not valid time like 26:53
. I also can't use am
or pm
, only 24h format. The pattern seems to work only for one symbol. How can I use it for more characters? Something like this ([01]?[0-9]|2[0-3])
I also try to validate value after input:
$("input").each(function() {
el = $(this);
el.mask("Hh:Mm", {
onComplete: function(cep) {
if (!/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(cep)) {
alert('Error');
el.attr("value","");
}
},
translation: {
'H': { pattern: /[0-2]/ },
'h': { pattern: /[0-9]/ },
'M': { pattern: /[0-5]/ },
'm': { pattern: /[0-9]/ }
}
});
});
This solution is not so good because I still allow the user to type something wrong. How can I fix this?
I found a solution to this problem using a function mask
var maskBehavior = function (val) {
val = val.split(":");
return (parseInt(val[0]) > 19)? "HZ:M0" : "H0:M0";
}
spOptions = {
onKeyPress: function(val, e, field, options) {
field.mask(maskBehavior.apply({}, arguments), options);
},
translation: {
'H': { pattern: /[0-2]/, optional: false },
'Z': { pattern: /[0-3]/, optional: false },
'M': { pattern: /[0-5]/, optional: false}
}
};
$('.daytimemask').mask(maskBehavior, spOptions);
this seems to work fine, but it's necessary to add the left zero on hours before "12".
I hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With