Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time validation 24h-Format in jQuery Mask Plugin

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?

like image 235
eurocups Avatar asked Dec 18 '22 18:12

eurocups


1 Answers

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.

like image 192
alejosr Avatar answered Jan 14 '23 11:01

alejosr