Oct 17 2008

meioMask – a jQuery mask plugin

fabiomcosta @ 13:16

meioMask for Mootools!

meioMask’s page at jquery.com

meioMask’s Git project page

Menu

meioMask download

Encoding is important if you are going to use the mask with special characters like áéã (rule ‘@’, see below for more). If you are going to allow these characters at your masked inputs and your page enconding is not UTF8, then you should add the charset attribute with value UTF8 to your script tag, like so:

<script type="text/javascript" src="jquery.meiomask.js" charset="utf-8"></script>

meioMask features

  • Accepts paste event;
  • Has fixed and reverse mask types ( allow number mask );
  • You can still use your hotkeys and others (ex: ctrl+t, ctrl+f5, TAB …);
  • Supports metadata plugin;
  • Works with iPhone;
  • Allow default values;
  • Has callbacks for invalid inputs, valid and overflow;
  • Has function to mask strings;
  • And much more!

meioMask compatibility

meioMask has been tested with jQuery 1.7.2 on all major browsers:

  • Firefox2, Firefox3, Firefox3.5 (Win, Mac, Linux);
  • IE6, IE7, IE8 (Win);
  • Chrome (Win, Mac, Linux);
  • Safari3.2, Safari4 (Win, Mac, iPhone, yes, it supports iPhone!);
  • Opera (Win, Mac, Linux).

meioMask usage

It’s a snap to use:

<!-- include jquery library and meioMask plugin -->
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.meiomask.js" charset="utf-8"></script></p>

<script type="text/javascript">
  // call setMask function on the document.ready event
  jQuery(function($) {
    $('input[type="text"]').setMask();
  });
</script>

<p>

meioMask options

It just has the options bellow that will be applyed by default if you don’t specify any.

$.mask.options = {
  attr: 'alt',              // an attr to look for the mask name or the mask itself
  mask: null,               // the mask to be used on the input
  type: 'fixed',            // the mask of this mask
  maxLength: -1,            // the maxLength of the mask
  defaultValue: '',         // the default value for this input
  textAlign: true,          // to use or not to use textAlign on the input
  selectCharsOnFocus: true, //selects characters on focus of the input
  setSize: false,           // sets the input size based on the length of the mask (work with fixed and reverse masks only)
  autoTab: true,            // auto focus the next form element
  fixedChars: '[(),.:/ -]', // fixed chars to be used on the masks.
  onInvalid: function(){},
  onValid: function(){},
  onOverflow: function(){}
};

meioMask fixed characters

FixedChars, as the name says, are the fixed characters that you will have on your mask. For example if you mask is ’99/99/99′ you will probably want to have the ‘/’ to be a fixedChar. So the fixedChars value can be ‘[/]‘.

By default meiomask has some fixed characters that can be used to make the masks. You can change the regular expression that matches the fixed chars by changing the ‘fixedChars’ string. The default one is ‘[(),.:/ -]‘.

meioMask rules

Rules are symbolic characters that match a certain regular expression. meioMask has some defined rules but you may add yours to the rules object.

Making masks will be explained further, and you’ll understand how to glue all this stuff :P .

meioMask defined rules:

$.mask.rules = {
  'z': /[a-z]/,
  'Z': /[A-Z]/,
  'a': /[a-zA-Z]/,
  '*': /[0-9a-zA-Z]/,
  '@': /[0-9a-zA-ZçÇáàãéèíìóòõúùü]/
};

!! There are still the number rules. They will be created ‘on-the-fly’ so if you create a rule that is a number it will be overwritten!

Number rules are:

$.mask.rules = {
  '0': /[0]/,
  '1': /[0-1]/,
  '2': /[0-2]/,
  '3': /[0-3]/,
  '4': /[0-4]/,
  '5': /[0-5]/,
  '6': /[0-6]/,
  '7': /[0-7]/,
  '8': /[0-8]/,
  '9': /[0-9]/
};

meioMask masks

Defined masks:

$.mask.masks : {
  'phone'         : { mask : '(99) 9999-9999' },
  'phone-us'          : { mask : '(999) 9999-9999' },
  'cpf'           : { mask : '999.999.999-99' },
  'cnpj'          : { mask : '99.999.999/9999-99' },
  'date'          : { mask : '39/19/9999' }, //uk date
  'date-us'       : { mask : '19/39/9999' },
  'cep'           : { mask : '99999-999' },
  'time'          : { mask : '29:69' },
  'cc'            : { mask : '9999 9999 9999 9999' }, //credit card mask
  'integer'       : { mask : '999.999.999.999', type : 'reverse' },
  'decimal'       : { mask : '99,999.999.999.999', type : 'reverse', defaultValue: '000' },
  'decimal-us'        : { mask : '99.999,999,999,999', type : 'reverse', defaultValue: '000' },
  'signed-decimal'    : { mask : '99,999.999.999.999', type : 'reverse', defaultValue : '+000' },
  'signed-decimal-us' : { mask : '99,999.999.999.999', type : 'reverse', defaultValue : '+000' }
}
You may add yours to the $.mask.masks Object. Like this:
$.mask.masks.msk = {mask: '999'}
This code will add a mask called ‘msk’ to the masks Object. Now you can use an input with the ‘attr’ atribute set to this new mask. Like this:

Input with the ‘msk’ Mask
<input type="text" alt="msk" />

All the options from the plugin are accepted to be used at a mask you define.

If you want to add more than one mask it will be better to do this:

$.mask.masks = $.extend($.mask.masks, {
  msk:         { mask: '999' },
  other_msk:   { mask: '6666' },
  another_one: { mask: '7777', type:'reverse' }
});
You can put any other options on a new mask that you create (fixedChars for example.)

meioMask demos

standalone

Example form with defined masks
<input type="text" id="cc" name="cc" alt="cc" />
<input type="text" id="time_example" alt="time" />
<input type="text" id="decimal" value="12345" name="some_name" alt="decimal" />

meioMask paste feature demo

We now will see the paste feature of this plugin, and how nice it is. I want you to copy some texts and paste them on the input. You’ll see that it just pastes what is corret for the field.

Example form for the paste feature copy: 1234567890 and paste at the input copy: (12) 3456-7890 and paste at the input copy: 12abcdef34567890 and paste at the input
<input type="text" id="phone" name="phone" alt="phone" />

They will all give the same result! Imagine your visitor using it! It’s the way he want’s it to be!

with metadata plugin

You can always change metadata plugin settings. See they’re page for more information.

Metadata Plugin page

Metadata will always overwrite the ‘attr’ value. Look these examples to make it more clear.

Example form with masks using metadata plugin metadata overwrote the ‘(99) 666′ mask set at alt attribute
<input type="text" id="metadata1" class="{mask:'555-666'}"  alt="(99) 666" />
metadata overwrote the ‘phone’ mask set at alt attribute
<input type="text" id="metadata1" class="{mask:'555-666'}"  alt="phone" />
<input type="text" class="{mask:'666-888'}" />

change mask on-the-fly

Example form with the change-on-the-fly feature
<input type="text" id="change_mask" alt="(99) 666" maxlength="10" />
You can use it like you do with most of jQuery functions, chaining other functions. At this example the code for the first button is:
$('#change_mask').setMask('***:***').val('');
This code sets the mask for all the elements that matches the selector ‘#change_mask’ to ‘***:***’ and then set it’s value to ”.

mask string example

Example that shows the $.mask.string() function
<input type="text" id="dump_input" />
              (function($) {
$('#lmask_string1').click(function(){
$('#masked_string').text( 'Masked value: "'+$.mask.string( $('#dump_input').val(), '99/99/99' )+'"' );
return false;
});
$('#lmask_string2').click(function(){
$('#masked_string').text( 'Masked value: "'+$.mask.string( $('#dump_input').val(), 'phone' )+'"' );
return false;
});
$('#lmask_string3').click(function(){
$('#masked_string').text( 'Masked value: "'+$.mask.string( $('#dump_input').val(), {mask:'999.999,999',type:'reverse'} )+'"' );
return false;
});
})(jQuery);

read-only inputs

Example that shows a readonly input working as it should (some plugins breaks this!)
<input type="text" readonly="readonly" alt="decimal" />

callbacks example

Example with a input and defined callbacks
<input type="text" id="cb_test_input" />
And the javascript:
          $('#cb_test_input').setMask({mask:'99.99-99/99',defaultValue:'000',
onInvalid:function(c,nKey){
$('#cb_alerts').text('You can\'t input "'+c+'" in here. It\'s keynumber is "'+nKey+'".');
$(this).css('background','red');
},
onValid: function(c,nKey){
$('#cb_alerts').text('"'+c+'" is ok. It\'s keynumber is "'+nKey+'".');
$(this).css('background','#40FF3F');
},
onOverflow: function(c,nKey){
$('#cb_alerts').text("You can't enter more characters but your input might be ok!");
$(this).css('background','green');
}
});

signed masks example

Example with signed masks (‘-’ and ‘+’ keys will change they’re signal)
<input type="text" alt="signed-decimal" />
<input type="text" value="-4445" alt="signed-decimal" />
<input type="text" class="{mask:'99,999.999',type:'reverse',defaultValue:'-000'}" />

‘repeat’ mask type example

This mask makes it possible to have values with infinite or defined length in a input. It doesn’t support fixedChars.

Input with a mask of type repeat
<input type="text" class="{mask:'9', type:'repeat'}" />
<input type="text" class="{mask:'9', type:'repeat', 'maxLength': 7}" />

Note: both the attribute maxLength and the option maxLength will work for setting the max length for the repeat mask.

$().unmaskedVal example (deprecated)

!!! This function has been deprecated, because it does not work correctly for all the masks but it should be easy for you to implement yours. !!! This function removes all the FixedChars from the value of the input and returns it.

Click on the link to see the unmaskedVal return
<input type="text" value="3456" alt="decimal" id="unmasked_input" />
This link has this code:
<a onclick="jQuery('#unmasked_string').html( jQuery('#unmasked_input').unmaskedVal() );return false;" href="#">Get the unmasked value from the input</a>

Changelog

v1.1.2

  • Set defaultValue property of the input. This fixes the behavior of the reset button on forms. Now the value will be reseted to the masked value;
  • âêô were added to the ‘@’ rule;
  • Fix for the auto-tab feature, it now focus just on visible form elements;
  • Added setSize option. It sets the input size based on the length of the mask (work with fixed and reverse masks only).

v1.1.1

  • Fixed caret bug on ‘repeat’ masks;
  • Fixed keyup event on fixed masks, it is now firing propertly;
  • Added selectCharsOnFocus option;
  • Added textAlign option.

v1.1

  • Mask type ‘infinite’ is now called ‘repeat’ (using ‘infinite’ still works but it is deprecated). It now allows a maxLenght value to be set. MaxLength can be set by the maxLength attribute of the element or the maxLength option;
  • You can easily set an autoTab option that will focus the next form element when the masked input is totally filled. It is true by default but you can put a jQuery selector string to match the next element you want to be focused.
  • Deprecated ‘unmaskVal’ function. This function is too buggy… works for most cases but not all. The best way to unmask a value is by doing it yourself;
  • The fixedChars option is not global anymore, giving more flexibility for the masks;
  • ‘phone-us’ mask is now ‘(999) 999-9999′;
  • Correctly fires the onChange event on reverse masked inputs.

v1.0.4

  • New mask type ‘infinite’, it allows infinite values at masks. See demos for a better understanding;
  • Added new function ‘unmaskVal’ that returns the input value without the mask. See demos for a better understanding;
  • Removed a serious bug at IE that was fixing the caret at the end of the input;

v1.0.3

  • Callback functions now receive the char number as it second parameter, so it is possible to detect exactly which key has been pressed;
  • Added the signed masks. It only works with the reverse mask. See demos for more details;
  • iPhone support improved. iPhone now works 100% better than the 1.0.2 version. I’ts logic have been changed, and now it’s working with full features. :P

v1.0.2

  • Added input callbacks: onInvalid, onValid and onOverflow;
  • Added support for default values;
  • Can now be used like $().setMask({});
  • Added the function $.mask.string(string,mask) that will mask a string (see demos);
  • Now the value of the input is masked at the time the mask is applyed to it.

v1.0.1

  • Added support for iphone;
  • Removed a bug where a fixed char would be replaced by an inputed one.

v1.0

  • Initial release.

License

All this documentations and examples are under the Open Source MIT License.

The MIT License

Copyright (c) 2008 Fábio Miranda Costa

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

393 Responses to “meioMask – a jQuery mask plugin”

  1. Marcelo says:

    Olá Fábio,

    Seu plugin é excelente. Aparentemente há um problema no tratamento dos decimais quando estes são zero. Por exemplo: quando declaro o número 1500 como valor inicial de uma tag input, a máscara ‘{“mask”:”99.9999″,”type”:”reverse”}’ apresenta “15.00″ e não “1500.00″.

    A solução imediata que encontrei foi formatar os valores com duas casas decimais antes de jogá-los no input. No exemplo acima, o número enviado foi “1500.00″. Estou à disposição para contribuir, se for possível.

    Um abraço, Marcelo

  2. Bulat says:

    Thanks dude =)

  3. jQuery表单美化-增强插件 | Yovae Blog says:

    [...] meioMask – a jQuery mask plugin [...]

  4. Victor Melo says:

    Olá, eu gostaria de saber se o meiomask me possibilita que o conteúdo do campo(sem a máscara!) seja submetido para o servidor? Como faço?

    Grato,

    Victor.

  5. fabiomcosta says:

    @Victor voce pode pegar o valor sem mascara com a funcao unmaskedVal, existe um exemplo nesta pagina: http://www.meiocodigo.com/projects/meiomask/#mm_unmaskedval

  6. Victor Melo says:

    Perfeito Fabio!

  7. Anup Das Gupta says:

    Hi,

    Great plugin.

    Time mask has an issue. It takes 25 to 29 as input value for hour which is not correct.

    Regards Anup

  8. Leandro Sciola says:

    Excelente plugin!

    Sugestão:

    Adaptar o plugin para os novos números de celular com 9 dígitos.

    “phone-9″:{mask:”(99) 99999-9999″}

    A máscara TIME tem um “bug”. Exemplo: 29:59

  9. Rudá says:

    Problem with the iPhone, does not work when you put for example: 9999-9999

    Try entering 12345678 When he puts it – the position is wrong.

    It does not remove.

  10. Rudá says:

    Problema no iPhone, não funciona quando coloca por exemplo: 9999-9999

    Tente digitar 12345678 Quando ele coloca o – a posição fica errada.

    E não funciona o remover.

  11. Nelson says:

    Parabéns pelo plugin! Reforçando o pedido do Fernando. Gostaria de saber como faço para usar 2 mascaras de forma que a mascara seja alterada automaticamente no momento da digitação. Exemplo: (99)9999-9999 – Quando for residencial 2 dígitos DDD + 8 (99)99999-9999 – Quando for celular São Paulo 2 digitos DDD + 9.

  12. Samuel C says:

    Fábio, grande plugin cara, parabéns. Odeio aquelas mask que fica sendo exibida no input: [( ) - ] Manjo muito pouco de javascript, mas conseguir fazer uma pequena alteração no código, quando você seta a mascara para data 99/99/999 por exemplo, enquanto a pessoa digita ex: [15 ] as vezes ela mesma digita parte da mask [15/ ], mas o plugin não deixava “onOverflow” o caracter aparecer.

    Tentei criar uma regra para data mas fail me heheheh: ‘dd’ : /0[1-9]|[012][0-9]|3[01]/ vlw cara

  13. Daniel says:

    Definitivamente o melhor plugin de input mask de todos os tempos. Parabéns! Opinião dada após muitos anos utilizando outros plugins e mais de 1 ano utilizando o seu plugin.

  14. Matheus says:

    Pessoal, no link abaixo o Danilo MR postou uma solução.

    http://www.guj.com.br/java/266551-mascara-telefone-mudanca-para-aceitar-9-digitos

  15. Igor says:

    css:text-transform don’t work with your plugin((

  16. skynetweb says:

    to fix the time issue just change this around line 149 to ‘time’: {mask: ’23:59′ }, instead of ‘time’: {mask: ’29:59′ },

  17. Josi says:

    Olá gostaria de saber como criar uma mascara para limitar a digitação de valores no input até o valor 10,00. Estou tentando {mask:’00.01′,type:’reverse’}, mas não tá rolando. Alguma idéia?

  18. Danilo says:

    Prezados,

    Há possibilidade de mostrar a máscara no campo com undercore quando o campo não estiver preenchido?

    Ex: 99/99/9999 -> //____

  19. Sergiy says:

    Thank you for great product! I use yours mask technology with Richfaces 3.3 and 4 and very happy with this solution! :)

  20. Junior Pacheco says:

    Fabio, tenho dois campos: Valor Unitario e Valor Promocional. no evento onblur do valor unitário eu faço um cálculo de porcentagem e retorno este valor no campo Valor Promocional. Esse valor não fica mascarado. Como faço?

  21. 55个jQuery表单美化/增强插件 | Hsinchu says:

    [...] meioMask – a jQuery mask plugin [...]

  22. 15个非常有用的jQuery表单插件 | CTOSPACE.COM says:

    [...] meioMask (Input field mask plugin) [...]

  23. 迅捷服务 » 15 个非常有用的 jQuery 表单插件 says:

    [...] meioMask (Input field mask plugin) [...]

  24. 15 个非常有用的 jQuery 表单插件 | 光子时代 says:

    [...] meioMask (Input field mask plugin) [...]

  25. Paulo Correia says:

    è possivel usar uma regular expression como mascara ? se sim vc pode colocar um exemplo

  26. guillaume says:

    Hi, Can meiomask be used for the following requirements ? I need a time mask (ex. “11:35″) having this behaviour : - For “11:35″, when typing “1″, then “1″ again, the “:” separator should be displayed instantly, not after typing “3″ - For “09:07″, user should be able to type “9″ and “7″ only, because 9 > 2 (2 would be the max value of the first digit, “23″ being the max value for the hours part); and because 7 > 5 (5 would be the max value of the third digit, “59″ being the max value of the minutes part). Thanks in advance !

  27. 15 个非常有用的 jQuery 表单插件 « 后代码 says:

    [...] meioMask (Input field mask plugin) [...]

  28. mike says:

    Hi,

    There is definitely a bug with IE8, win7, using the phone mask. If you enter a phone number as normal, then click off (blur focus), then click back so all the numbers are highlighted, then start typing a number it happens. The first digit you type gets overwritten by the second. So if you type in 206-233-2333, then go back in and type in 506-233-2333, the 5 will get overwritten by the 0. It’s like the cursor moves backwards on its own.

    Please help, otherwise I love it but this is kind of a big deal since it’s on a hospital website.

    -Mike

  29. Elias says:

    Para a máscara do nono dígito:

    $('#ELEMENTO').setMask("99999-9999").keypress(function() {
    if($(this).val().length ==8 || $(this).val().length==9) { if($(this).val().length > 8) { $(this).unsetMask(); $(this).setMask("99999-9999"); } else { $(this).unsetMask(); $(this).setMask("9999-9999*"); } } });

  30. Elias says:

    Corrigindo o post anterior, este é código correto:

    $('#ELEMENTO').setMask("9999-9999").keypress(function() {
    if($(this).val().length ==8 || $(this).val().length==9) { if($(this).val().length > 8) { $(this).unsetMask(); $(this).setMask("99999-9999"); } else { $(this).unsetMask(); $(this).setMask("9999-9999
    "); } } });

  31. Elias says:

    Corrigindo o post anterior, este é código correto com o asterisco * depois do último nove:

    $('#tel_area_comercial').setMask("9999-9999").keypress(function() {
    if($(this).val().length ==8 || $(this).val().length==9) { if($(this).val().length > 8) { $(this).unsetMask(); $(this).setMask("99999-9999"); } else { $(this).unsetMask(); $(this).setMask("9999-9999
    "); } } });

  32. Sammnrve says:

    how call setmask with live ?

  33. Leandro says:

    Na versão 1.9.1 do jQuery foi removida a função $.browser, e por esse motivo ele gera alguns erros. Para resolver o problema, que inclusive acontecia com outros plugins, criei um arquivo logo após a inclusão do jQuery no cabeçalho com o código

    jQuery.browser = {}; jQuery.browser.mozilla = /mozilla/.test(navigator.userAgent.toLowerCase()) && !/webkit/.test(navigator.userAgent.toLowerCase()); jQuery.browser.webkit = /webkit/.test(navigator.userAgent.toLowerCase()); jQuery.browser.opera = /opera/.test(navigator.userAgent.toLowerCase()); jQuery.browser.msie = /msie/.test(navigator.userAgent.toLowerCase());

    Peguei o código do seguinte site http://pupunzi.open-lab.com/2012/08/14/jquery-1-8-and-browser-detection/

  34. herz-atk says:

    Olá! Tudo bem?

    Estou tendo um erro com o meioMask e a versão mais recente do JQuery. O erro acontece só de importar o meioMask, o erro é o seguinte: “Uncaught TypeError: Cannot read property ‘opera’ of undefined”

    Se precisar de mais informações para reproduzir o erro eu lhe informo.

    Abraços e obrigado!

  35. Van says:

    Hi, Great mask.

    How could I make this work with HTML5′s input=”number” though?

    I’ve changed:

    $(‘input[type="text"]‘).setMask();

    to

    $(‘input[type="number"]‘).setMask();

    But it doesn’t work. What else do I need to modify?

  36. Alan says:

    There is a bug with the TIME MASK! damn it. Please fix it. If I mask 23:59. I can’t write from 14:00 to 19:00.

  37. Lincoln says:

    Alan, if you think that there’s something wrong, you should feel free to fix it and send a patch to the maintainer. Also, you should thank him for the work he did so far, not complain about one or another bug that you may find on it.

    “Talk is cheap, show me the code” — Torvalds. L

  38. Jillustre says:

    Is it possible to remove the paste event, or at least not permit to keep wrong data in the field?

    Ex: with ctrl-V put letter in textbox that only accept number. stay ctrl v key down in the input field then click outside… it keep the letter…

  39. victor neves says:

    O framework ainda permanece instável com iphone. Fiz uma máscara para dinheiro assim:

    $.mask.masks.moeda = {mask: ’99,999.999′,type:’reverse’};

    E quando estou digitando o valor ele apaga o campo antes de colocar a vírgula! Ele me permite digitar até o segundo dígito, quando vou digitar o terceiro e quando ele deveria botar a vírgula ele apaga o campo inteiro!

  40. Paul says:

    Hello,

    Whenn I can do a mask that only accept integer ? and not delimited number of caracters ?

    Thanks

Leave a Reply