Oct 17 2008
meioMask – a jQuery mask plugin
Menu
- Download it!
- Features
- Compatibility
- Usage
- Options
- FixedChars
- Rules
- Masks
- Demos
- Changelog
- License
- Post Comment
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
.
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:
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
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.
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 will always overwrite the ‘attr’ value. Look these examples to make it more clear.
change mask on-the-fly
mask string example
read-only inputs
callbacks example
signed masks example
‘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.
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.
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.
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.

September 28th, 2011 19:28
Hola, necesito una máscara que me permita ingresar apóstrofes, por ejemplo d’alessandro. Es compatible con firefox 6? Gracias, el plugin está muy bueno.
October 5th, 2011 07:45
Great plugin!
But how can I make mask that pasts the fixedChar (for example ‘-’) to the end of input? So I need my input text shuld be seem like “13212-12312-12312-”.
October 10th, 2011 05:02
[...] meioMask allows 999.999.999.999,99 format, but the value is converted to string. The binding with Double in Java fails. [...]
October 19th, 2011 08:53
Is there any option for masking fractional numbers ? I want to mask the fractional numbers with precision upto two decimal places. for example : 3,.56,65.78,193.67,32455.78 with the same mask.
October 19th, 2011 09:21
Is there any option for masking fractional numbers ? I want to mask the fractional numbers with precision upto two decimal places. for example : 3.56, 65.78, 193.67, 32455.78 with the same mask.
October 19th, 2011 09:51
Thanks for help in advance . Is there any way to apply two masks at the same time ???
October 27th, 2011 09:27
Hello, i´m new to jQuery and I can´t put this module to work. I don´t understand why putting the mask name into the “alt=” attribute would activate the mask code for that HTML element. I added to my html the text bellow that loads meioMask
And I also set the mask I wanted activated into the “alt” attribute:
But that is not working. Am I missing something obvious that wasn´t mentioned in this documentation?
October 27th, 2011 14:24
Hello all, i just wanted to document here that now it’s working. The problem is I didn’t really wrote the code that I’ve shown above. The code above works fine, thanks.
October 28th, 2011 03:47
[...] Meio Mask [...]
November 3rd, 2011 19:04
hi!,I like your writing very much! proportion we communicate extra about your article on AOL? I need an expert on this house to resolve my problem. Maybe that’s you! Taking a look forward to see you.
November 14th, 2011 20:48
Olá.
Estou precisando usar uma máscara de moeda, para um campo de % de desconto. Como devo proceder? Olhei nos exemplos mas não consegui.
Usando a mascara de moeda eu tenho o resultado que preciso, mas o valor máximo deve ser 99,99%.
Obrigado!
November 21st, 2011 15:14
[...] meioMask – a jQuery Mask Form Input Plugin [...]
November 21st, 2011 19:48
[...] Em primeiro lugar vamos fazer download do mesmo AQUI [...]
November 24th, 2011 15:58
Essa mascara para valores 999.999,99 não permite valores baixos, tem que encher de zero à esquerda para se ter as casas decimais após a vírgula.
November 24th, 2011 16:04
[...] Demo | Source page [...]
November 26th, 2011 14:31
[...] A JQuery Mask Plugin [...]
November 29th, 2011 14:24
Excellent I love it! Thankss thanks thanks
November 30th, 2011 03:45
Very nice plugin. To bad that it doesn’t work with Internet Explorer 9
November 30th, 2011 08:18
Fabio, fantastico plugin! Seguem 2 sugestoes pro site e 1 bug.
Sugestoes: - Colocar a data dos releases (tanto no changelog quanto no download da versao atual – nao faco ideia se a versao que eu estou usando e’ a mais nova ou nao!) - Colocar seu nome em local mais visivel, perto do topo (meioMask by Fabio…)
Bug (ou eu estou fazendo algo errado?): - Na mascara de hora, nao aparece o zero da dezena dos minutos (“3:05″ aparece como “3:5″)
Abs
December 9th, 2011 14:18
Bom dia, Poderia me ajudar? Preciso de uma mascara para o CMC7. Estou usando o seu plugin versão 1.0.1.
Em tese, a mascara deveria ficar da seguinte forma: <99999999999999999999Ç
O meu problema esta sendo o “Ç”, ele não aparece como último caracter. Para os caracteres “<” e “>” adicionei eles em “fixedChars:” dentro da mascara mesmo, ai funcionou.
Obrigado.
December 20th, 2011 10:54
Muito bom o plugin, pena que vai ser descontinuado pra jQuery.
December 22nd, 2011 07:28
Nice plugin Fabio! My question is that, lets say my textbox value is ’123456′ and I want to put ’0′ in to the beginning (like ’0123456′). When I try to do this, mask put the last entered value to the end although the cursor is set to beginning. Is there any way to do this? Thanks in advance.
December 22nd, 2011 09:27
@Erdi, what you are asking for is working fine here. What’s your browser? Cheers,
December 22nd, 2011 17:38
Have you thought about turning this into a WordPress plugin?
December 26th, 2011 22:50
Perfect!
January 4th, 2012 21:57
Maybe you want to update plugin to use some HTML5 stuff. For example, using data attributes makes your plugin more clean I think.
But I should congratulate you; good job!
January 5th, 2012 10:33
[...] meioMask for jQuery [...]
January 30th, 2012 02:43
[...] Demo | Source page [...]
February 1st, 2012 11:19
[...] meioMask [...]
February 8th, 2012 08:12
Can we add mask like (999) 999-9999 ext.9999 ?
February 8th, 2012 14:22
[...] meioMask – a jQuery mask plugin [...]
February 21st, 2012 03:19
[...] meioMask – a jQuery mask plugin [...]
February 25th, 2012 01:43
[...] meioMask – a jQuery facade plugin [...]
March 1st, 2012 12:51
I will use your plugin but I can not mask some dynamically added row html controls rows in a table
March 5th, 2012 13:01
[...] meioMask – a jQuery mask plugin [...]
March 6th, 2012 06:03
[...] Ajax Fancy Captcha is a jQuery plugin that helps you protect your web pages from bots and spammers. Captcha’s security level is medium, with the emphasis on nice looking and user friendly qualities while still offering reasonable protection from unwanted “guests”. It has a basic design and its elements are easy to style and customize. View the Demo » meioMask – a jQuery Mask Form Input Plugin [...]
March 14th, 2012 11:42
Muito bom, parabéns e obrigado! Uma dúvida, tem como fazer um validação para somente aceitar no formato da mascára?
April 12th, 2012 14:10
Muito bom Fábio, obrigado pelo plugin.
Uma dúvida tem como colocar mais de um mask pro mesmo campo? Com a “nova” regra do CNPJ ele aceita tanto 99.999.999/9999-99 e 999.999.999/9999-99 então teria como fazer um mesmo campo receber as duas validações?
Obrigado mais uma vez.
April 17th, 2012 13:48
É uma pena seu pluggin não ser mais atualizado nesta versão. Foi o melhor que já pude encontrar até hoje. Infelizmente ele não está funcionando nas versões mais novas do SAFARI, conseguentemente iPhone e Ipad.
Parabéns pelo trabalho, voto pela continuação da versão jQuery!
April 22nd, 2012 08:54
Tambem foi um dos melhores que achei. Com suporte ao eventos de copiar e colar …
Algum plano de continuar a versão para jQuery ?!
April 22nd, 2012 09:03
Achei uma legal pra quem precisar: http://cwolves.github.com/jQuery-iMask/
April 28th, 2012 08:48
[...] meioMask comes with lot of configuration options. It has a large number of defined masks. It also allow to add additional mask. MeioMask is compatible with all major browsers. [...]
May 2nd, 2012 14:22
Desde já parabéns pelo plugin. Um observação, parece que quando utilizada a rules (regras)’Z'(maiúsculo) é aplicada, não funciona.
May 10th, 2012 13:52
[...] meioMask – a jQuery Mask Form Input Plugin [...]
May 11th, 2012 15:51
[...] meioMask – a jQuery mask plugin [...]
May 21st, 2012 17:16
[...] http://www.meiocodigo.com/projects/meiomask/ [...]
May 21st, 2012 17:22
[...] meioMask Plugin is there any way to set up a mask so it will accept valid time in 24h or even better in 12h [...]
May 28th, 2012 11:48
Fantastic plugin, using it for quite a few projects including this one. It’s a shame that you have abandoned jquery for mootools.
May 31st, 2012 11:21
Yo, thanks for the plugin, great work. Hope you continue it for jQuery
Best wishes Ron
June 1st, 2012 14:54
[...] Posiblemente, este sea uno de los plugins más prácticos. Te permite crear máscaras para limitar la entrada de datos en los campos del formulario para que se adecuen a fechas, datos numéricos, números con decimales, etc. Máscaras para formularios – Demo [...]