igorescobar / jQuery-Mask-Plugin

A jQuery Plugin to make masks on form fields and HTML elements.
http://igorescobar.github.io/jQuery-Mask-Plugin/
Other
4.77k stars 1.42k forks source link

Masking hour and prevent incorrect hours #778

Open ghost opened 2 years ago

ghost commented 2 years ago

Hello guys, i have m little funcion to mask a input from time, the owner just ask for not use htm l input type='time', that why I'm using input text.

How I can prevent incorrect hour like 25:55 or 19:99

here jfddelr: http://jsfiddle.net/2oxak786/

THanks

hax18 commented 2 years ago

I'm currently having the same problem, if u find an answer please let me know in the comment.

sacerro commented 2 years ago

Hi, You can use "translation" setting to achieve this. For example:

$('#hour_field').mask('AB:CD', {
    translation: {
      A: { pattern: /[1-2]/  },
      B: { pattern: /[0-4]/ },
      C: { pattern: /[0-5]/ },
      D: { pattern: /\d/ },
    }
  });

Hope this help!

sercit commented 2 years ago

Hi, You can use "translation" setting to achieve this. For example:

$('#hour_field').mask('AB:CD', {
    translation: {
      A: { pattern: /[1-2]/  },
      B: { pattern: /[0-4]/ },
      C: { pattern: /[0-5]/ },
      D: { pattern: /\d/ },
    }
  });

Hope this help!

Hi! Unfortunately, that's not the best way, cause it's possible to set 14:xx , but not possible to set 19:xx.

I think, the best solution will be callback and filter incorrect values on it

Martin12350 commented 2 years ago

So the best solution right now is this I guess:

var options = {
    placeholder: 'hh:mm:ss',
    translation: {
        2: {pattern: /[0-2]/}, 
        3: {pattern: /[0-3]/}, 
        5: {pattern: /[0-5]/},
        9: {pattern: /[0-9]/}
    }, onKeyPress: function(cep, e, field, options) {
        var masks = ['23:59:59', '29:59:59'];
        var mask = (cep.charAt(0) !== '2') ? masks[1] : masks[0];
        field.mask(mask, options);
    }
};

$('.time').mask('23:59:59', options);

You can omit 9 and replace with 0, but this is more readable, at least for me. Also '29' is not a typo for '19', it is there because otherwise once You would put 1, You would never be able to write 2 again.