How to perform multiple masks on demand in an input field

I am trying to mask an input using the jquery mask plugin . I need to do two different masks:

US ### - ### - ### - ### - ### - ### this mask should be applied if the user dials some numbers first. (Which here I mean entering a digit by #)

but if the user chose not to type numeric data first, I want him to enter any letters or symbols or unicod numbers (any character entirely) after that

How can I accomplish such a mask?


source to share

1 answer

One possible solution could be using what is called the jQuery Mask Plugin doc plugin On-the-fly mask change

as shown below:


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



    var options =  {onKeyPress: function(us){
        var masks = ['CAAAA-AAA-AAA-AAA-AAA-AAA', 'US000-000-000-000-000-000'];
            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);



The problem with your input is that it uses the S character. Although S already has a different meaning in the plugin. According to the default legend:

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


So, you have two options for solving this problem: use the translation template or override the default parameters in "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", for example "C". It could be a different symbol.

Check out this jsfiddle link to see a working example.

Hope this is helpful!



All Articles