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. Thank Igor for this plugin, I’m trying to implement it, but what I need is the following.
    $(“.iItemQty”).mask(‘#,##9.00’, {reverse: true}); I tried it to use it with: 12,345,678.90 and it doesn’t work, just display: 5,678.90.. so, I had to add the rest as follow:
    $(“.iItemQty”).mask(‘###,###,##9.00’, {reverse: true}); what happened with # ?? I thought I could add any number quantity.

    The second issue is about: 00,432,234.88, as you can see 0s on the left must to be remove them given the value is a number instead a string.

    A similar case, I’ll save 432234.88 in the database, how can get the value with mask back again ?

    Any clue?
    Thanks.

    Like

  2. What if I want to use this by just dropping the js onto the page and not having to explicitly call mask for each class? The docs say I should be able to do this but that doesn’t work. It never makes it into $(‘*[data-mask]’).each(function()…

    Like

  3. Hi igore,

    I am using jquery 1.7 but thisnot seems to be working .Split was not happening.Can you please let me know does this plug in support jquery 1.7 or it required any other libraries??Please help me in this regard.

    Like

  4. Então brother, coloquei uma mascara opcional na versão que eu tenho e queria falar com você sobre isto =D, se possivel, pega meu email ai.

    Like

  5. The puglin doesn’t work to me. I’m trying to make a web app in Ruby on Rails and I already added it to my application, but I cannot apply it in my text fields, it just doesn’t mask it. I tried inut the class with :class => ‘ip_adress’ and input_html sintax, but just doesn’t work. Can you help me please?

    Like

  6. I have been trying unsuccessfully to do US currency using the html data-mask attribute. It should allow a format of 1,000,000.00 with the “.00” being something that is optional. How can I make the period and two digits to be optional?

    Like

    1. @Iaacov upgrade your plugin and make sure you’re calling all your javascript files at the bottom of your HTML document. If you want to enable HTML Notation for dynamically inserted data-mask elements you need to set
      $.jMaskGlobals.watchDataMask = true;

      Like

  7. Hello,

    Great plugin, but following question has arisen: when i use the normal date mask, is it possible to have trailing ‘_’ so the user could see how much he still has to type?

    like “12.12.20__” ?

    kind regards Jan

    Like

  8. First of all it is a good plugin 🙂 but it is not working in samsung s3mini related models ‘GT-I8190’, ‘SM-G730A’, ‘GT-I8190N’, ‘GT-P5100’

    Like

  9. How to create a mask for first digit will be a number with 6 or 8 or 9 and total number length will 9 in mask jquery.
    Like as : 658452123
    or 887545265
    956458712
    I need first digit will be 6 or 8 or 9 otherwise it will be else

    Like

  10. how to restore the original mask setting when the reset button is triggered? When the reset button is clicked, it wipes out all mask settings.

    Like

  11. Nice plugin!
    How can I mask this phone?
    8 (926) 000-000-000
    where 8 (926) are predefined.

    But when I apply this mask ‘9’ will be replaced..

    Like

  12. Hello,
    I’m trying to figure if there’s a way to use the on-the-fly mask to accept phone number input in two different ways?
    I want to allow people to enter 000-0000 or (000) 000-0000. Most of the time users just need to enter 7 digits, but there are rare occasions when the person may have a need to use 10 digits. Is that possible with the on-the-fly-mask?

    Thanks for your help.

    Like

  13. Hi,
    Only the number of characters of the mask istaken in accont, not the other effects.
    By example with a mask specified like this (’00/000′):
    I get this:456123
    but not this: 45/123

    Like

  14. Great plugin, love its flexibility. However, it isn’t clear how one would do a mask for email addresses — using your translation parameters does allow for regular expressions but it seems like you need to type in the precise amount of alphanumeric characters in the mask declaration, which is obviously not something one can predict for email addresses. Note that I am not the only person wondering about this:

    http://stackoverflow.com/questions/28780184/jquery-mask-plugin-to-mask-email-addresses-and-web-urls

    Would you be able to provide an example here for how that might be done? I appreciate your help here. Thanks, j

    Like

  15. hey there Igor! first of all thank you for this awesome piece of software! its a life saver! i got a question tho: how can i make it work with brazillian portuguese accentuation like Çç ã á À é, i might have done something wrong. i’m using it as follows

    $(‘.mask_only_letters_ws’).mask(‘S’,{
    ‘translation’: {S:{pattern: /[A-Za-z ]/, recursive: true}}
    });

    Thanks!

    Like

  16. I need to replace my mask library and this looks great. The one I am using now does not allow me to copy paste. I have a big question. My current mask uses 9 for numbers , your seems to be 0. But I also see 9s so is there any difference bettwen using 9 or 0?

    Thank you

    Like

  17. OPA Igor estou tentando fazer uma máscara para pegar somente : espaço traço – e alfanuméricos sem com no Max 200 caracteres…

    Estou tentando assim :
    $(“#meuId”).mask (“AAAAAAAAAA”);
    Como posso fazer pra não colocar tantos A’s… exemplo A* assim funcionaria para várias entradas e o espaço e o traço ainda nem Vi.

    Abraço

    Like

  18. I’m using your plugin and it’s great. The only thing I can’t figure out is how to compare the input field as numeric against a numeric field from a database or using it in jQuery min, or calculations, etc.
    example: using mask on 3 fields where:
    A + B must equal C
    1,200 + 0 = 1,200 returns true (Valid)
    600 + 600 = 1,200 returns false (Invalid)
    HELP please!
    Thanks

    Like

  19. This is probably a simple thing for you…
    I want to append a http://www. to the front of my pattern
    “W”: { pattern: /[\w/\-.]/, recursive: true }
    Any ideas? I searched around a lot but came up short.. if I could figure this out I will defiantly use your plugin and leave a tip. Thank you!

    Like

  20. Olá, não estou conseguindo usar as máscaras usando a notação html data-mask=”00/00/00″, a máscara funciona apenas no primeiro elemento de meu formulário onde apliquei a tag, nos demais não funciona e nenhum erro é gerado.

    O que posso estar fazendo de errado?

    Grato

    Like

  21. Hello, Igor! Thank you for such a helpful plugin.
    When I try to edit text in the field with mask, it works strange.
    For example:
    $(‘.phone’).mask(‘0000-0000’);
    1. I entered 1234-5678.
    2. I try to edit entered phone number and place cursor between 1 and 2
    3. I enter 9.
    I expect to replace 2 by 9 and move cursor between 9(was 2) and 3
    But I see 1923-4567 in masked input field and cursor steel stands between 1 and 9

    Please answer, is it a bug? Can it be fixed?

    Like

  22. hi dear.
    thank you for your project.

    i just have a question about jquery mask plugin.
    how i can make an unlimited mask for a text input ???

    Like

  23. Salve Igor! Parabéns pelo Plugin TOP! Estou fazendo uns testes e se o plugin me atender 100%, vou pingar no seu Pledgie

    Estou enfrentando duas situações, e gostaria de saber se tem como resolver :

    1. Usar 2 Function Mask (A do telefone – como do seu exemplo), e repliquei para o CPF/CPNJ da mesma forma. No entanto, quando começa digitação, parece que se perde, e mesmo sendo formatação de CNPJ, ele começa colocando os ‘()’ do DDD, e termina bloqueando como CPF.

    2. Na formatação para valores, como posso formatar valores negativos ?

    Grande abraço.

    Like

  24. Olá,

    o callback onComplete não identifica o input que está sendo alterado?
    Estou tentando pular para o próximo input usando:
    onComplete: function(){ $(this).next(‘input’).focus();}

    Poderia me dar um auxílio nisso?

    Like

  25. Hi, Its a very nice plugin and very easy to use.

    I just came across one issue. Its working fine on the Web but once we open the same page on a smart device, after entering 2 characters it move 1 character back.

    Any solution or update for that? Thank You

    Like

  26. Olá Igor,

    Esse plugin está ótimo! Só preciso configurar o atributo money para incluir o prefixo “R$” é possível?

    Like

  27. Hi, Its a very nice plugin and very easy to use.

    how i can get the key pressed with option onKeyPress ?

    thank you in advance

    Like

  28. Hi,

    Can you help me with the mask
    What I want is input text with regular but if I use ‘#’ like this:

    $(“#xxx”).mask(‘#’, {
    ‘translation’: {
    ‘#’: { pattern: /[一-龠]+|[ぁ-ゔ]+|[ァ-ヴー]+|[a-zA-Z0-9]+|[a-zA-Z0-9]+[々〆〤]/ ,optional: true}
    },maxlength: true
    });

    Then it allows me to input only 1 character! How can I set to no limit input?

    Thank you

    Like

  29. Hello friend, frist of all congratulations for this great component. I’m using it and masks work fine, but properties like reverse or selectOnFocus don’t work, do you have any idea what can cause this? Why just mask works?

    Thanks.

    Like

  30. First of all great plugin.

    But its still missing a validation that clears the field if i dont finish filling the form.

    ex: date dd/mm/yyyy and i write dd/mm

    it shoud clear the input since the values are not optional.

    Like

  31. Hello,
    Great work!

    Could you pease help me?

    Your code
    ————————
    $(document).ready(function() {
    $(‘.field-name’).mask(‘SS00 0000 0000 0000 0000 00’, {
    placeholder: ‘____ ____ ____ ____ ____ __’
    });
    });
    ———————-

    is it possible to place defaut FR insted of SS in the mask field.
    In the out put i want to enter only FR not other alphabets.

    Please help me

    Like

  32. Hi, beautiful tool you have! 1 problem that is bothering me though:
    upon storing “masked” data, it adds a pipe | symbol at the end.
    How do i get rid of that?

    Like

Leave a comment