Masks With jQuery Mask Plugin

Today is the oficial release of the version 0.4.3 of my jQuery Mask Plugin. Since I have never written about it before on this blog, I’ll teach you guys how to use it and some other cool features about it.

Downloading the code

 wget https://github.com/igorescobar/jQuery-Mask-Plugin/blob/master/jquery.mask.min.js 

The only thing that you guys need to do is include the javascript file of the plugin between the head tag in your HTML document and it’s all set to use.

(\___/)
( ͡ ͡° ͜ ʖ ͡ ͡°)
\╭☞ \╭☞ Follow me on Twitter!

The syntax

The jQuery Mask Plugin syntax is pretty simple. First, you input your  selector, followed by the .mask and then as a parameters you have to put the mask that you want the plugin to apply on the form field.
Example

[javascript]
$(document).ready(function(){
  $('.date').mask('00/00/0000');
});
[/javascript]

In this example the mask 00/00/0000 will be applied in all the input fields that have the “.date” class. At jQuery Mask Plugin you don’t have pre-established masks, you choose the mask as you wish. On the website project you can see the jQuery Mask Plugin running with some others examples like this:

[javascript]
$(document).ready(function(){
$('.date').mask('11/11/1111');
  $('.time').mask('00:00:00');
  $('.date_time').mask('00/00/0000 00:00:00');
  $('.cep').mask('00000-000');
  $('.phone').mask('0000-0000');
  $('.phone_with_ddd').mask('(00) 0000-0000');
  $('.phone_us').mask('(000) 000-0000');
  $('.mixed').mask('AAA 000-S0S');
  $('.cpf').mask('000.000.000-00', {reverse: true});
  $('.money').mask('000.000.000.000.000,00', {reverse: true});
});
[/javascript]

As you can see, it’s possible to define other data type on each digit of the mask. This mask for example:

[javascript]
$('.mixed').mask('AAA 000-S0S');
[/javascript]

The user can type a sequence of three alpha numeric characters, followed by space, three numeric characters, a slash, one string character, other number character and finally one string character, cool isn’t it?

Again, you can define the mask as you wish and the data type of each digit of the mask as well.

Features

  • Lightweight (~2kb minified, ~1kb gziped).
  • Masks on any HTML element!
  • data-mask attribute support.
  • String/Numeric/Alpha/Mixed masks.
  • Reverse mask support for masks on numeric fields.
  • Sanitization.
  • Optional digits.
  • Digits by range.
  • Automatic maxlength.
  • Advanced mask initialization.
  • Callbacks.
  • On-the-fly mask change.
  • Mask removal.
  • Customization.
  • Compatibility with Zepto.js

More about jQuery Mask Plugin

  1. jQuery Mask Plugin on Github
  2. Demonstration
  3. jQuery Mask Plugin
  4. All versions of jQuery Mask Plugin

Any problems, please, let me know.

Help us!

http://igorescobar.github.io/jQuery-Mask-Plugin/

148 thoughts on “Masks With jQuery Mask Plugin

    1. Oi Claudio,

      Não existe uma implementação default no evento onComplete. Estes eventos foram criados para que vocês, usuários, possam dar utilidade a ele. Então, se você quer que no onComplete ele pule para o próximo campo, você tem que implementar o código no onComplete da Mascara.

      Like

  1. Igor,

    Eu queria colocar uma regra para um campo “numérico”, que só aceitasse números, mas poderia ser de qualquer tamanho.

    É possível vc colocar alguma forma de repetição? Tipo um ‘9*’ na máscara?

    Like

  2. Igor, i tried to use mask function, but it affects my other functions called on keyup events. My other functionality stops working even when i tried using the mask() on blur() & then removing it as below, on focus() of the field, still other functions on keyup does not work.
    $(‘.date’).data(‘mask’).remove();

    I want to format the credit card number field with (9999 9999 9999 9999) & at the same time i have to check the type of card depending on its initial 4 digits & display the corresponding image. my image display code on keyup event doesnt work if i use this plugin.

    Like

  3. Bem legal teu plugin, principalmente por resolver o 9º dígito.
    Tenho uma sugestão: colocar um evento no blur (onBlur).

    Fiz dessa forma, na função seekCallbacks:
    if (options.onBlur && e.isTrigger === undefined && typeof options.onBlur == “function”) {
    $el
    .off(‘blur.mask’)
    .on(‘blur.mask’, function(){
    options.onBlur(oNewValue, e, currentField, options);
    });
    }

    Deve ter uma forma mais elegante de fazer, principalmente por esse off que eu precisei incluir pois estava duplicando os eventos.

    Abraço

    Like

    1. Pelo código que você está usando vejo que você está usando uma versão antiga do plugin. Recomendo que atualize. Por quê você acha que deve ser o onblur e não no onkeyup? Gostaria de entender sua perspectiva. Abraços!

      Like

  4. Prezado Igor,

    Primeiramente gostaria de parabenizá-lo pelo código!

    Seria possível definir uma máscara fixa, por exemplo 2013NE00001????
    Em que fosse necessário apenas a digitação dos últimos 5 dígitos, ficando os 6 primeiros fixos?

    Like

    1. @Fabio, hoje não existe uma feature especifica para fazer isso que você quer. Se te ajuda, você pode criar um campo readonly com este pre-fixo e depois aplicar a mascara “00000” em um segundo campo. Na hora de cadastrar você soma o valor dos 2 campos. Infelizmente, hoje não tem esta feature mas está anotado, vou pensar em algo, existe varias coisas bacanas que estou esboçando para implementar mas não vejo o jquery mask suportar esta feature em um curto prazo.

      Like

  5. Hi Igor, One question I hope you can answer, is there a way I can change the event when the masking occurs?? Actually it occurs onkeypressed right? (I guess), but is there a way to change it in order to occur onblur? Thanks in advance!! Great job by the way!!

    Like

  6. Hi Igor, I need to allow the user to decide when (in what event) to apply the masking, if it’s possible, but ok, I should find another solution, thank you very much!!

    Like

  7. @Garcia!

    I see your point. I just want to know what is your “use case” to understand the real “need” of something like that and see if that is interesting to implement on jQuery Mask Plugin’s core.

    Cheers,
    Igor.

    Like

  8. Hi Igor
    Congratulations for this plugin, I like to know how can I add place holders to the input mask. Eg: Zip Code: _____-____
    Thanks

    Like

  9. Igor, thanks a lot for this plugin!
    I tried to create a mask for a phone number (US format), using an optional extension :
    (999) 999-9999 x9999 (The ” x9999″ part is optionnal). In fact, the ” x” should appear automatically if more numbers are entered. Is there a way to make this work?

    I understand how to use optional caracters, but I can’t figure out how to make this work…

    Like

  10. Yes it works! Thank you Igor.

    I made a little tweak, so the extension number length is variable :

    $(‘.phone_us’).mask(‘(999) 999-9999 x9{1,5}′, {maskChars: {“x”:”x”}});

    Like

  11. Hi Igor,

    Great work on the plug-in. Quick question, is there a way to allow the optional input of a (‘-‘ hyphen) in the money mask. I know that the mask can be configured to allow a single string character at a specific placeholder or an alpha-numeric character. But I would like to restrict the input to only the – hyphen as to allow for negative values. For example:

    $(“#” + element).mask(‘-?000,000,000,000,000’, { reverse: true });

    Like

    1. I see what you’re trying to do but unfortunately isn’t possible. I could not focus to cover all possible features to money fields, just the simple ones. The code should stay fit. In that case, I suggest you to use a “money plugin”.

      Like

  12. Hi,
    Thank you for this nice plugin.
    I would like to use it to use it money format, is it possible to display a currency symbol in the input field??

    Thank you in advance

    Like

  13. Olá Igor,
    Parabéns pelo trabalho, é um ótimo plugin, tem atendido a necessidade perfeitamente.

    Porém, gostaria de mascarar latitude e longitude, mas não tenho obtido sucesso pois as máscaras devem ter o caractere – (menos/negativo) como opcional. Alguma forma de me ajudar?

    Obrigado.

    Like

  14. Hello,

    Thank you for your great plug in for jquery. I am trying to use “on the fly mask change” but couldn’t achieve what i want to do.

    I am trying to apply a phone number mask depends on the entered characters length. There are 3 masks that could be applied to input field, these are;
    (00) 000 000 00 00
    (000) 000 000 00 00
    (0000) 000 000 00 00

    I have tried the sample which is on demonstration page but it only apply mask for the first pattern and dont let me enter more chars.

    Thanks in advance.

    Like

  15. Hi Igor,

    I also tried that yesterday but this time it doesnt automatically format the phone number. It always gets the first four digits into parantheses. I want it to do this if length is longer than the first pattern. Is it possible?

    Thank you.

    Like

    1. Sure it is!
      But your code is going to be a little bit different. Take a look into our documentation page:
      http://igorescobar.github.io/jQuery-Mask-Plugin/

      There you’re going to see a section called “On-the-fly mask change”. Using that callback you can see what your user are typing at the same time he is pressing its keyboard keys. You can use a mask like this:
      (00) 000 000 00 009″ then you check if its value length is higher or equal of 19.. if it’s true you change the mask to (000) 000 000 00 009 and so on.

      Hope it helps.

      Like

  16. I have a text input where I use the US phone mask

    $(‘#myInput’).mask(‘(000)-000-0000″);

    which works for the data input. I then use .getCleanVal() to get just the digits for the phone number and store them in the database.

    For editing, I retrieve the phone number from the database as just digits and set the val() of the input

    $(‘#myInput’).val(‘1234567890’);

    However, when the value is set the mask is not applied and the input field looks like this

    1234567890

    rather than

    (123)456-7890

    What do I have to do differently?

    Like

    1. Hi @Chris!

      That is because jQuery Mask Plugin only monitor “real-user” events. The fact that you are inserting data via javascript doesn’t trigger any event that’s why your mask isn’t applied. Everytime you set an input value with the .val() method make sure that you are manually triggering the keyUp event.

      $(‘.field’).val(‘1234’).keyup();

      It should work for you.

      Like

  17. It seems line when I use the default A and S values the users can type special characters like &^$)(. It that what was intended and is there a way to limit it to just the alphabet characters?

    Thanks!

    Like

  18. Hai,
    I m using mask function for my date of birth field.
    After entering date for example 23/06/1980 and when I try to delete a character in the middle then the characters are shifting towards left.
    In the example if I delete 6 then it is formatted to 23/01/980.
    Is there any solution for the characters not to shift towards left.

    Like

  19. Igor have have tried the things in the documentation and they have not worked. Not sure what I am doing wrong. It appears to be ignoring my {maxlength: fale} attribute.

    Also can we put any regex syntax we like in the translation?

    Like

  20. @chris the pattern key on the translation option is to you define the group of characters that is valid of a X digit.
    ex:

    ‘A’: {pattern: /[a-zA-Z0-9]/},

    A is valid if anything typed on its place matches with /[a-zA-Z0-9]/

    inside of that /[……….]/ you can put any characters you like.. including unicode characters.

    Like

  21. Bonjour,
    Comment mettre un retour à la ligne dans un même masque pour avoir :
    AA-
    123-AA
    comme sur les plaques d’immatriculation des motos ???
    Pour l’instant, j’ai inséré dans un champ “input” : $(“#numplaque”).mask(“aa-999-aa”); ça fonctionne mais sur 1 seule ligne…
    Merci beaucoup !
    —————————————————
    Hello,
    How to put a newline in a same mask for:
    AA-
    123-AA
    as on the license plates of motorcycles??
    For now, I inserted in a field “input”: $ (“# numplaque”) mask (“aa-aa-999”) it works but, on one single line. …
    Thank you so much!

    Like

  22. Sorry maxlength: false.

    Also whenever I put certain characters like ^%*& in the pattern the mask seems to be ignored. In aspx what is the escape character I need to use? I have tried all the ones that seemed likely.

    For instance I have {translation: {‘E’:{pattern:/[a-zA-Z0-9]/, recursive: true}}} because I want an alphanumeric where the user can enter as many characters as they want.

    I tried just using .mask( ‘A’,{maxlength: false}) but it would only allow one character so either my format is wrong or I do not understand the maxlength attribute.

    Like

  23. I am building the mask at run time based upon data type. Here is what the resulting html looks like:

    jQuery(function($){$( ‘input[id=”ctl00_ctl00_ctl00_mainContentPlaceHolder_SecondLevelContentPlaceholder_ThirdLevelContentPlaceHolder_txtLeadCaseName”][type=”text”][DataType=”AlphaNumeric”]’ ).mask(‘A’,{translation: {‘A’:{pattern:/[a-zA-Z0-9/],recursive: true}}});});

    Like

  24. Hi Igor ,

    i tried to make mask begin from right to left for for Arabic date like this :

    2007/12/01 i need start typing from right to left .. i hope you catch what i mean 🙂

    i hope u catch what i mean 🙂

    thanks for help

    Like

  25. hello Igor

    thanks for replay … i tried this function but it gave me wrong structure ..
    i type 2007/12/10 —> i had like this 1012/20/07 .

    Like

  26. Hi Igor,
    the mask is great, but I have a problem.
    When I use the masking with a multiple selector, like this:
    $(‘[name$=”taxNumber”]’).mask(‘00000000-0-00’);
    I get a comma, at the end of the numbers, like this: 12345678-9-10,
    with this:
    $(‘#taxNumber’).mask(‘00000000-0-00’);
    everything is fine.
    Any idea how to avoid this extra charater?

    Like

  27. I Need to know if i can show the mask on a input on focus without having to type anything in.

    Thanks guys!

    Like

  28. Hi Igor,

    I have tried your plug-in.
    It is working if I apply mask in jquery .
    But data-mask property is not working for text box.

    Thanks in advance.

    Like

  29. Hi Igor,

    Thanks for the quick response.
    But for me , below line is also not working.

    Note: my input control is in another contentplaceholder and my script is in another contentplaceholder.

    Like

  30. Hi, really like the plugin and would love to include in some work we are doing here in New Zealand. We are using jQuery 1.5.1, but when I grab the mask plugin code for that version of jQuery, it’s throwing an error in this code:

    destroyEvents: function() {
    el.off(‘keydown.mask’).off(“keyup.mask”).off(“paste.mask”);
    },

    as ‘off()’ isn’t defined as function. Looking at the jQuery docs, it looks like off() wasn’t introduced until version 1.7 of jQuery.

    I was wondering if there was a way around this? Upgrading our jQuery version isn’t an option at this stage unfortunately.

    Thanks so much.

    Like

    1. Hi @Rachel. I’m think that you have to create the function “.off” and “.on” to make it work and make it as a proxy to the method “.unbind” and “.bind”. The another problem is that the plugin use all events under the namespace “mask” as you can see and I don’t know if it is available at that stage of jQuery. Take a look at the Compatibility section at jQuery Mask Plugin Repository: https://github.com/igorescobar/jQuery-Mask-Plugin#compatibility

      Like

  31. Olá,

    Gostaria de saber como eu faço para tirar o autofocus que o plugin adiciona ao input automaticamente?

    Obrigado!!

    Like

  32. Hello Igor,

    Trying to add a dollar sign or currency symbol to a mask such as

    $(‘.money’).mask(‘#,###,###,##0’, {reverse: true});

    Tried adding .mask(‘$#,###,###,##0’, {reverse: true});
    Doesn’t show the $

    Tried adding .mask(‘#,###,###,##0\$’, {reverse: true});
    Puts the symbol in the wrong place

    Tried this as well .mask(‘#.##$0,00’, {reverse: true});

    Do I need to make this a function or is there a way to add the currency symbol in the pattern?

    Thanks,
    Jw

    Like

  33. Por favor puede orientarme como usar la expresión regular ‘[A-Za-z0-9\b]+’ como mascara de un campo tipo texto

    Gracias

    Like

  34. Gracias Igor. I was wondering why the optional digits weren’t working for me on decimal values, but it turns out I had an old version of the plugin. Downloaded the latest version (1.6.4 as of this writing), and it works perfectly. Nice work, thank you. -Dave

    Like

  35. I am trying to use your mask plugin with mvc4.

    I am relatively new so I might not understand as much as I need to. I have the

    in my layout page

    the jquery.mask.mask.js, jquery.mask.min.js in my scripts folder

    and this in my view

    $(document).ready(function () {

    debugger;
    $(‘.phone’).mask(“(999) 999-9999”);

    $(“.phone”).on(“blur”, function () {
    var last = $(this).val().substr($(this).val().indexOf(“-“) + 1);

    if (last.length == 3) {
    var move = $(this).val().substr($(this).val().indexOf(“-“) – 1, 1);
    var lastfour = move + last;
    var first = $(this).val().substr(0, 9);

    $(this).val(first + ‘-‘ + lastfour);
    }
    });
    });

    when running the page I get an “Uncaught TypeError: undefined in not a function” error when $(‘.phone’).mask(“(999) 999-9999”); is hit.

    do I need the json files in my project? where? Script folder?

    any help will be appreciated. Thank you

    Like

    1. @Javier use a validation plugin. you are probably wondering how to do it because you don’t want to validate/sanitize your input field. There is no such thing as e-mail mask.

      Like

Leave a comment