Skip to content
Leo Caseiro edited this page Sep 18, 2015 · 10 revisions
<script src="/meiomask/jquery.js"></script> <script src="/meiomask/jquery.metadata.js"></script> <script src="https://raw.github.com/fabiomcosta/jquery-meiomask/master/jquery.meio.mask.min.js"></script> <script type="text/javascript"> jQuery(function($) { $('input[type="text"]').setMask(); }); </script>

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

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 ...);
  • Works with iPhone;
  • Allow default values;
  • Has callbacks for invalid inputs, valid and overflow;
  • Has function to mask strings;
  • And much more!

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

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

options

These are the default available options:

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

'fixedChars' option

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 together :P.

meioMask defined rules:

$.mask.rules = {
  'z': /[a-z]/,
  'Z': /[A-Z]/,
  'a': /[a-zA-Z]/,
  '*': /[0-9a-zA-Z]/,
  '@': /[0-9a-zA-ZçÇáàãâéèêíìóòôõúùü]/,
  '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]/
};

masks

Pre-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 your own masks to the $.mask.masks object:

$.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' attribute set to this new mask:

<input alt="msk" type="text" />

// TODO inline some jsfiddles? (if not allowed, link them)

Input with the 'msk' Mask Msk:

All the previously mentioned options are accepted to be used with your own created masks.

demos

Standalone demo at JsFiddle

<h3 id="mm_standalone">standalone</h3>
<form action="index_submit" method="get"> <fieldset>
<legend>Example form with defined masks</legend>
<label for="cpf">Credit Card:</label>
<input id="cc" alt="cc" name="cc" type="text" /> 

<label for="time_example">Time:</label>
<input id="time_example" alt="time" type="text" />

<label for="decimal">Decimal number:</label>
<input id="decimal" alt="decimal" name="some_name" type="text" value="12345" />

</fieldset>
</form>

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 correct for the field.

Copy and Paste at JsFiddle

<form action="index_submit" method="get">
<fieldset>
<legend>Example form for the paste feature</legend>
<label for="cpf">Phone example:</label>
copy:  <strong>1234567890</strong> and paste at the input
copy:  <strong>(12) 3456-7890</strong> and paste at the input
copy:  <strong>12abcdef34567890</strong> and paste at the input
<input id="phone" alt="phone" name="phone" type="text" />
</fieldset>
</form>

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

change mask on-the-fly

Demo Change Mask on The Fly on JsFiddle

<form action="index_submit" method="get"> <fieldset>
<legend>Example form with the change-on-the-fly feature</legend>
<label for="change_mask">Mask '(99) 666':</label>
<input id="change_mask" alt="(99) 666" maxlength="10" type="text" />
<ul>
  <li><a onclick="jQuery('#change_mask').setMask('***:***').val('');return false;" href="#">Change mask to '***:***'</a></li>
  <li><a onclick="jQuery('#change_mask').setMask('(aaa) **-9999').val('');return false;" href="#">Change mask to '(aaa) **-9999'</a></li>
  <li><a onclick="jQuery('#change_mask').unsetMask().val('');return false;" href="#">unset the mask</a></li>
</ul>
</form>

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

Mask string example on JsFiddle

<form action="index_submit" method="get">
<fieldset>
<legend>Example that shows the $.mask.string() function</legend>
<label for="dumb_input">Enter any input:</label>
<input id="dump_input" type="text" /> <em id="masked_string"></em>
<ul>
  <li><a id="lmask_string1" href="#">Mask input value to '99/99/99'</a></li>
  <li><a id="lmask_string2" href="#">Mask input value to 'phone'</a></li>
  <li><a id="lmask_string3" href="#">Mask input value to {mask:'999.999,999',type:'reverse'}</a></li>
</ul>
<script type="text/javascript">
  (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);
</script>
</fieldset>
</form>

read-only inputs

Read-only at jsfiddle

<form action="index_submit" method="get"> <fieldset>
<legend>Example that shows a readonly input working as it should (some plugins breaks this!)</legend>
<label for="readonly_input">Mask '999.999.999,99':</label>
<input alt="decimal" readonly="readonly" type="text" />
</fieldset>
</form>

callbacks example

// TODO move this to a jsfiddle

<form action="index_submit" method="get"> <fieldset>
<legend>Example with a input and defined callbacks</legend>
<label for="cb_test_input">Mask '99.99-99/99':</label>
<input id="cb_test_input" type="text" />
<em id="cb_alerts"></em>
<script type="text/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');
    }
  });
</script>
</fieldset>
</form>

signed masks example

// TODO move this to a jsfiddle

<form action="index_submit" method="get"> <fieldset>
<legend>Example with signed masks ('-' and '+' keys will change they're signal)</legend>
<label for="signed_mask1">Mask 'signed-decimal':</label>
<input alt="signed-decimal" type="text" />
<label for="signed_mask2">Mask 'signed-decimal' with negative value at input:</label>
<input alt="signed-decimal" type="text" value="-4445" />
<label for="signed_mask3">Mask '999.999,99', reverse, with defaultValue='-000' (this example uses the metadata plugin):</label>
<input class="{mask:'99,999.999',type:'reverse',defaultValue:'-000'}" type="text" />
</fieldset>
</form>

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

// TODO move this to a jsfiddle

<form action="index_submit" method="get"> <fieldset>
<legend>Input with a mask of type repeat</legend>
<label for="repeat_mask1">Mask '9' (this example uses the metadata plugin):</label>
<input class="{mask:'9', type:'repeat'}" type="text" />
<label for="repeat_mask2">Mask '9' with maxLength 7 (this example uses the metadata plugin):</label>
<input class="{mask:'9', type:'repeat', 'maxLength': 7}" type="text" />
</fieldset></form>

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.

// TODO move this to a jsfiddle

<form action="index_submit" method="get">
<fieldset>
<legend>Click on the link to see the unmaskedVal return</legend>
<input id="unmasked_input" alt="decimal" type="text" value="3456" /><em id="unmasked_string"></em>
<ul>
  <li><a onclick="jQuery('#unmasked_string').html( jQuery('#unmasked_input').unmaskedVal() );return false;" href="#">Get the unmasked value from the input</a></li>
</ul>
</fieldset>
</form>

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.