
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.jsThe 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
Any problems, please, let me know.
Ele pula para o próximo campo no onComplete?
LikeLike
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.
LikeLike
Valeu Cara!
Muito Bom o Trabalho!
LikeLike
@Leandro Valeu! Qualquer sugestão e/ou dúvida, é só falar 😉
LikeLike
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?
LikeLike
Hoje, nao tem suporte para isso
LikeLike
Parabéns belo trabalho!
LikeLike
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.
LikeLike
Saurabh,
Which jQuery version are you using?
– Igor
LikeLike
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
LikeLike
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!
LikeLike
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?
LikeLike
@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.
LikeLike
Igor,
Muito obrigado pela atenção! Tentarei implementar sua dica! e espero anciosamente pelo seus esboços!
LikeLike
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!!
LikeLike
Hi Garcia!
Actually, no. But what exactly are you trying to do? what kind of use case is this?
– Igor
LikeLike
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!!
LikeLike
@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.
LikeLike
It is a robust and customizeable plugin. Going to add in my list
Thanks
LikeLike
Hi Igor
Congratulations for this plugin, I like to know how can I add place holders to the input mask. Eg: Zip Code: _____-____
Thanks
LikeLike
Hi @Emilio, Thanks!
Maybe on a future release. Currently you can’t achieve this kind of place holder.
LikeLike
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…
LikeLike
Hi Cardin,
Check this example:
$(‘.phone_us’).mask(‘(999) 999-9999 x9999’, {maskChars: {“x”:”x”}});
And tell me if it works for you.
LikeLike
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”}});
LikeLike
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 });
LikeLike
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”.
LikeLike
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
LikeLike
In that case I strongly recommend you to use an “money” plugin.
LikeLike
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.
LikeLike
@Junior
Posta aqui o código que você está tentando usar.
LikeLike
Opa cara, estou aprendendo ember.js gostaria de saber se o plugin é compatível com o framework.
LikeLike
O plugin é testado com jQuery e Zepto.js. Não sei dizer se funciona com ember.js 🙂
LikeLike
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.
LikeLike
Hi @barbaros
What about: (0099) 000 000 00 00.
0 = required/mandatory digit.
9 = optional digit.
LikeLike
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.
LikeLike
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.
LikeLike
Hi Igor,
It works like a charm, thank you so much!
Regards.
LikeLike
Hi @Barbaros!
Glad you made it my friend 😉
LikeLike
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?
LikeLike
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.
LikeLike
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!
LikeLike
Take a look into our documentation page @Chris! There you can see how to personalize your regex to whatever you want 😉
LikeLike
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.
LikeLike
@srujana which version are you using?
LikeLike
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?
LikeLike
@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.
LikeLike
{maxlength: fale} FALE?
LikeLike
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!
LikeLike
Doesn’t work that way @LG. You can’t have multiline masks.
LikeLike
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.
LikeLike
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}}});});
LikeLike
If you are using recursive digits you have to set your maxlengh:
{translation: {‘A’:{pattern:/[a-zA-Z0-9/],recursive: true}}, maxlength: false}
LikeLike
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
LikeLike
@Falahj
What about:
$(‘.date’).mask(‘0000/00/00’, {reverse: true});
?
LikeLike
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 .
LikeLike
Is it possible to have placeholder in this plugin.
LikeLike
@Kamal Nope. Sorry.
LikeLike
Can I only define the type of character without format or maximum length?
LikeLike
@Johnny Take a look into our documentation at section “Recursive digits” and the maxlength option examples.
LikeLike
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?
LikeLike
@Dénes can you please provide a functional jsfiddle with the problem? Post your issue here: https://github.com/igorescobar/jQuery-Mask-Plugin/issues
LikeLike
Como faz pra permitir números negativos?
LikeLike
@hedron use um plugin especifico para resolver problemas monetários da parte monetária o plugin suporta só o básico.
LikeLike
I Need to know if i can show the mask on a input on focus without having to type anything in.
Thanks guys!
LikeLike
@Lucas currently, no. You the HTML5’s placeholder attribute.
LikeLike
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.
LikeLike
@Chandni the plugin isn’t tested on multi-line field. This is a unexplored area.
LikeLike
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.
LikeLike
@Chandni can you please provide a jsfiddle? Only then I can help you better.
LikeLike
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.
LikeLike
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
LikeLike
Olá,
Gostaria de saber como eu faço para tirar o autofocus que o plugin adiciona ao input automaticamente?
Obrigado!!
LikeLike
@Erick, veja se a versão v1.6.0 resolve o problema.
LikeLike
Could you please add donations via Flattr too?
LikeLike
@Mr. Dude Check it out! http://igorescobar.github.io/jQuery-Mask-Plugin/
Thanks 😉
LikeLike
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
LikeLike
@JW this jquery mask doesn’t have prefix/sufix support. Sorry.
LikeLike
Por favor puede orientarme como usar la expresión regular ‘[A-Za-z0-9\b]+’ como mascara de un campo tipo texto
Gracias
LikeLike
@mbenitezcol Por favor, eche un vistazo a nuestra documentación en la sección “Personalización”: http://igorescobar.github.io/jQuery-Mask-Plugin/
LikeLike
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
LikeLike
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
LikeLike
@John upgrade your plugin. also… the syntax has changed… so you should change it too.
LikeLike
Hey igor, what about a mask for Email? didn’t know how do it with ur plugin
LikeLike
@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.
LikeLike