jQuery-Mask-Plugin icon indicating copy to clipboard operation
jQuery-Mask-Plugin copied to clipboard

Masking hour and prevent incorrect hours

Open ghost opened this issue 3 years ago • 4 comments

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

ghost avatar Oct 04 '21 13:10 ghost

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

hax18 avatar Oct 07 '21 13:10 hax18

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!

sacerro avatar Dec 01 '21 11:12 sacerro

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

sercit avatar May 27 '22 09:05 sercit

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.

Martin12350 avatar Aug 15 '22 08:08 Martin12350