11

How do I specify an optional character in an input mask?

I found this masked input plugin http://digitalbush.com/projects/masked-input-plugin/ and these mask definitions.

$.mask.definitions['g']="[ ]";
$.mask.definitions['h']="[aApP]";
$.mask.definitions['i']="[mM]";
$.mask.definitions['2']="[0-1]";
$.mask.definitions['6']="[0-5]";
new_mask = "29:69";
$("#txtTime").mask(new_mask);

This defines an input mask for a 12 hour time format, e.g. 11:00. I'd like to allow the user to specify only one digit for the "hour". Instead of having to type 01:00, the user should be able to type 1:00. How do I do that?

Bruno Silva
  • 3,077
  • 18
  • 20
user823527
  • 3,644
  • 17
  • 66
  • 110

4 Answers4

6

You need to use ? for optional characters so in your case you should use "2?9:69".

Bruno Silva
  • 3,077
  • 18
  • 20
  • 1
    But this still doesn't allow the user to specify only one character for the hour. When I click out of the input field, the mask puts the minutes for the missing hour digit. – user823527 Mar 03 '12 at 02:00
  • 2
    Good catch, this seems like a bug in the plugin. Unfortunately, I don't know of a good solution for it unless you modify the plugin itself. – Bruno Silva Mar 03 '12 at 02:17
4

Quote and example from the page you linked to in your question:

You can have part of your mask be optional. Anything listed after '?' within the mask is considered optional user input. The common example for this is phone number + optional extension.

jQuery(function($){
   $("#phone").mask("(999) 999-9999? x99999");
});
Adam Zalcman
  • 26,643
  • 4
  • 71
  • 92
2

You can use $.mask.definitions['g']="[0-9 ]";

Jaqen H'ghar
  • 16,186
  • 8
  • 49
  • 52
user1047873
  • 230
  • 3
  • 8
  • 28
0

I have a similar problem I am trying to solve for variable currency amounts ($0.00 - $10000.00), and I don't really understand how the plugin is working.

On the one hand, the $.mask.definitions['symbol'] = '???' bit looks like it's employing a regex fragment, based on the examples in the API reference, and somewhat confirmed by this part in the source, within the mask function's code:

$.each(mask.split(""), function (i, c) {
    if (c == '?') {
        len--;
        partialPosition = i;
    } else if (defs[c]) {
        tests.push(new RegExp(defs[c]));
        if (firstNonMaskPos == null)
            firstNonMaskPos = tests.length - 1;
    } else {
        tests.push(null);
    }
});

...On the other, a mask definition of []|[0-9] does not work (I am attempting to do empty string or 0-9, for those not literate in regex.) For reference, I am attempting to build a mask to fulfill the 0.00-10000.00 condition like oooo9.99, where o is []|[0-9].

Since the code confirms that this is based upon regexes, the null or range pattern should be working but aren't; this is a more obscure bug in the mask framework. Unless I am the one trying to do something incorrectly, which is also possible...

Andrew Gray
  • 3,756
  • 3
  • 39
  • 75