How to perform multiple masks on demand on an Input field

user435245 picture user435245 · Oct 6, 2014 · Viewed 10.4k times · Source

Iam trying to perform a mask on input using jquery mask plugin, What I need to do is to perform two different masks:

US###-###-###-###-###-### this mask must be applied if the user is trying to type some numbers at first. (Which here I mean digit entry by #)

but if the user decided not to type any numerical at first I want to let him enter any kind of letters or unicod character or numbers (totally any character) after that

How should I perform such a mask?

Answer

Academia picture Academia · Oct 6, 2014

One possible solution may be using what is called in the jQuery Mask Plugin's doc by On-the-fly mask change, like following:

HTML:

<input type="text" class="US" maxlength="20" autocomplete="off"/>

jQuery:

$(document).ready(function(){
    var options =  {onKeyPress: function(us){
        var masks = ['CAAAA-AAA-AAA-AAA-AAA-AAA', 'US000-000-000-000-000-000'];
        if(us.length){
            mask = (us[0].match(/\d/)) ? masks[1] : masks[0];
            $('.US').mask(mask, this);
        }
        $('.US').mask('AAAAA-AAA-AAA-AAA-AAA-AAA', this);
    }};

    $('.US').mask('AAAAA-AAA-AAA-AAA-AAA-AAA', options);
});

Explanation:

The problem you have with your input is that it uses the character S. Although, S already has a different signification in the plugin. According to Default Mask Legend:

S: Only A-Z and a-z characters.

So you have two options to resolve this: use a translation pattern, or override the default options in the "jquery.mask.js":

var custom_options = {
  byPassKeys: [8, 9, 37, 38, 39, 40],
  translation: {
                '0': {pattern: /\d/}, 
                '9': {pattern: /\d/, optional: true}, 
                '#': {pattern: /\d/, recursive: true}, 
                'A': {pattern: /[a-zA-Z0-9]/}, 
                'S': {pattern: /[a-zA-Z]/}
            };
};

I choose the second one! I changed the 'S' by e.g 'C'. It could be another character.

Check this link jsfiddle to see a working example.

Hope it's useful!