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.

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

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

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:

$(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});
});

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

$('.mixed').mask('AAA 000-S0S');

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/

Posts Relacionados:

145 Comments

  1. Rashedul Hasan

    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

  2. Steven

    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.

  3. Gilou

    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

  4. James

    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

  5. Angelo

    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!

  6. jose

    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

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

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

  9. Trav

    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!

  10. Fabrício Fadel Kammer

    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

  11. Alice

    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?

  12. Alexandre Santos

    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.

  13. Arthur

    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?

  14. Abel

    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

  15. Kan Nguyen

    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

  16. Alexandre

    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.

  17. Arnaldo Paka

    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.

  18. aroul

    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

  19. Maarten

    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?

Leave a Reply

Your email address will not be published. Required fields are marked *