views:

1133

answers:

1

Using meioMask Plugin is there any way to set up a mask so it will accept valid time in 24h or even better in 12h system?

$(#txtTime).setMask('time');

This plugin has a pre-defined 24h 'time' mask but it's not quite correct, so you can enter invalid time values like "29:00". Is this mask is not suitable for this purpose and if not which one would be better?

+1  A: 

Try this:

$.mask.rules.H = /([0-1][0-9]|2[0-3])/;  // 24 hours
$.mask.masks.time = 'H:59';
$("#txtTime").setMask('time');

Correction:

The rules need to be for one character only, so having that in mind, you can swap the mask when the input starts with '2' and validate the next char to be [0-3]:

$("#txtTime").setMask("29:59")
.keypress(function() {
  var currentMask = $(this).data('mask').mask;
  var newMask = $(this).val().match(/^2.*/) ? "23:59" : "29:59";
  if (newMask != currentMask) {
    $(this).setMask(newMask);
  }
});

Note: In this case i'm using the keypress event, make sure to handle the paste event if needed.

Alex LE
Thanks for reply. Looks like this is a step in a right direction, but as it is doesn't accept any input at all:-)
Victor
I see, it seems like the meioMask plugin use a per char validation, I'll check if it allows multi-char rules.
Alex LE
It's all good except it won't allow some valid inputs that have 2 in them like I tried "23:32", won't let me input last "2"
Victor
I'll change the regex match to ^2.*
Alex LE
With that, works great, the only thing I had to change is to handle keydown event instead, or after 3rd number it just moves cursor over 1 left, don't know why.
Victor
In the last edit I fixed only changing the mask when needed, btw it's also a performance improvement too ;-)
Alex LE