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.
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.
LikeLike
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()…
LikeLike
@Robert upgrade your plugin.
LikeLike
A última versão é compatível com o jquery 1.7.1?
LikeLike
Is it possible to call the mask function without an element. E.g.($.mask(string, format))?
LikeLike
@David the plugin already support masks on non-input elements. You should try! You there is no public method capable of only apply the mask on your string.
LikeLike
É possivel restringir as horas de [00:00] a [24:00]? obrigado
LikeLike
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.
LikeLike
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.
LikeLike
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?
LikeLike
Make sure your version is upgraded.
LikeLike
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?
LikeLike
Hi Igor,
How to initialize the plugin to use HTML notation?
Calling $(‘.myInput’).mask() fails due to the empty mask.
LikeLike
@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;
LikeLike
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
LikeLike
@Jan the closest to it that you will get it’s by using the placeholder option.
LikeLike
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’
LikeLike
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
LikeLike
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.
LikeLike
@david there is no tricky way to do this… There someone using the reset button nowadays?
LikeLike
‘SS’ as a mask is not limiting to only upper case letters. Is this the correct approach?
LikeLike
@Aaron No. Checkout the docs. S stands for A-Za-z. You the translation object to personaliza this behaviour.
LikeLike
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..
LikeLike
Remove the 9 from the translation table 🙂
LikeLike
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.
LikeLike
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
LikeLike
Hi, tanks for the great component.
I need to implement a “multiple values masked field”.
Ex: Date mask => 10/10/2015;10/10/2016;10/10/2017…
is it possible ?
kind regards
LikeLike
How to use watchDataMask? I have read source code, but still can’t understand where to use this option
LikeLike
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
LikeLike
My apologies — I did a search on the page and didn’t see your earlier reply. In fairness, there is such a thing a an email mask:
http://www.jqueryscript.net/text/jQuery-Plugin-To-Mask-Email-Addresses-On-Your-Website-Mail-Mask.html
LikeLike
Answered your question at http://stackoverflow.com/questions/28780184/jquery-mask-plugin-to-mask-email-addresses-and-web-urls/34138169#34138169
LikeLike
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!
LikeLike
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
LikeLike
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
LikeLike
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
LikeLike
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!
LikeLike
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
LikeLike
how can I insert the charater “€” or “$” at the begin of the mask in a money field?
LikeLike
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?
LikeLike
Hello,
How can I define the numer of digits when I need to collect valid phone number?
I need it to have 9 digits.
HELP please!
Thanks 🙂
LikeLike
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 ???
LikeLike
i wanna to make unlimited count text Input.
thank you in advance
LikeLike
Hi,
Thank you for this awesome plugin. How can I mask a hex color input?
e.g
#333333
Regards.
LikeLike
Hello.
How to use the plugin with ZK?
thank you in advance
LikeLike
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.
LikeLike
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?
LikeLike
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
LikeLike
Olá Igor,
Esse plugin está ótimo! Só preciso configurar o atributo money para incluir o prefixo “R$” é possível?
LikeLike
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
LikeLike
To make sure no mask is visible on focus also set the showMaskOnHover to false. Otherwise hovering with the mouse will set the mask and will stay on focus.
LikeLike
Hi Igor. Very good plugin!!!
Can I remove the leading zeros from an IP address? For example: 192.168.070.071
LikeLike
Hola, como puedo hacer una mascara en html que acepte enteros negativos, gracias.
LikeLike
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
LikeLike
why does not work in textarea?
LikeLike
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.
LikeLike
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.
LikeLike
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
LikeLike
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?
LikeLike
The mask isn’t applying on dynamically inserted input values using .val(). How do you make this work?
LikeLike