user823527
user823527

Reputation: 3712

Optional character in input mask

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?

Upvotes: 11

Views: 29623

Answers (4)

user1047873
user1047873

Reputation: 268

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

Upvotes: 2

Andrew Gray
Andrew Gray

Reputation: 3790

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...

Upvotes: 0

Adam Zalcman
Adam Zalcman

Reputation: 27233

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");
});

Upvotes: 4

Bruno Silva
Bruno Silva

Reputation: 3097

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

Upvotes: 6

Related Questions