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?