Jquery.maskedinput js — документация на русском с примерами

Выполнить функцию после завершения ввода

Плагин также может выполнить функцию после завершения ввода:

$("#phone").mask("+7 (999) 999 - 9999",{completed:function(){alert("ОК!");}});

Маска ввода в полях формы на jQuery

Оригинал статьи Маска ввода в полях формы на jQuery

Masked input — очередной плагин предназначенный для всеми горячо любимого javascript фремворка jQuery, он позволяет облегчить жизнь вам и вашим пользователям, тем что с его помощью можно установить строгий формат ввода (маску ввода) в текстовые поля формы что хорошо подойдет для ввода времени, даты, телефона и т.п.

Плагин корректно работает во всех браузерах начитаная с IE6 +, FF 1.5 +, Opera, Safari, Chrome.

И так, что же нужно сделать для того, что бы начать использовать данный плагин на своем сайте? Для начала подключите javascript файлы jQuery и плагина к вашей странице, выглядеть это будет примерно так:

<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.maskedinput.js" type="text/javascript"></script>

Далее нужно вызвать функцию плагина для всех элементов формы для которых надо создать маску, и передать в нее необходимые параметры:

jQuery(function($){
   $("#date").mask("99/99/9999");
   $("#phone").mask("(999) 999-9999");
   $("#tin").mask("99-9999999");
   $("#ssn").mask("999-99-9999");
});

Функция плагина принимает 2 параметра первый — сама маска для ввода, второй — объект дополнительных параметров. Маска ввода представляет из себя строку состоящую из спец символов:

a — трактуется как буквенный символ из диапазона (A-Z,a-z)
9 — трактуется как числовой символ (0-9)
* — трактуется как алфавитно цифровой символ (A-Z,a-z,0-9)

Все символы кроме перечисленных выше трактуются как литералы.

В объекте дополнительных параметров можно указать заполнитель маски ввода, по умолчанию он равен _, к примеру вы захотели изменить его на пробел, тогда ваш код вызова функции плагина будет выглядеть примерно так:

jQuery(function($){
   $("#product").mask("99/99/9999",{placeholder:" "});
});

Так же в качестве дополнительного параметра можно указать функцию обратного вызова, которая будет вызвана после того как все элементы маски будут заполнены, например:

jQuery(function($){
   $("#product").mask("99/99/9999",{completed : function(){
       alert("Вы ввели: "+this.val());}
   });
});
Вы мож

ете использовать свои определения для спецсимволов маски ввода к примеру, вы хотите что бы пользователь мог указывать разность или сумму чисел тогда вы можете сделать это следующим образом:

jQuery(function($){
   $.mask.definitions='';
   $("#eyescript").mask("~9.99 ~9.99 999");
});

Иногда бывают такие ситуации, что возникает потребность не заполнять пользователем некоторую часть маски ввода, для этого вы можете использовать спецсимвол ? — все что идет после этого символа является не обязательным для ввода с стороны пользователя, например:

jQuery(function($){
   $("#phone").mask("(999) 999-9999? x99999");
});

Вот это наверное и все основные возможности данного плагина, используйте его в своих проектах и вы сделаете жизнь неопытного пользователя маленечко проще 🙂

Overview

This is a masked input plugin for the jQuery javascript library. It allows a user to more easily enter fixed width input where you would like them to enter the data in a certain format (dates,phone numbers, etc). It has been tested on Internet Explorer, Firefox, Safari, Opera, and Chrome. A mask is defined by a format made up of mask literals and mask definitions. Any character not in the definitions list below is considered a mask literal. Mask literals will be automatically entered for the user as they type and will not be able to be removed by the user.The following mask definitions are predefined:


  • a — Represents an alpha character (A-Z,a-z)
  • 9 — Represents a numeric character (0-9)
  • * — Represents an alphanumeric character (A-Z,a-z,0-9)

First, include the jQuery and masked input javascript files.

    npm install jquery-inputmask --dev    or    yarn add jquery-inputmask

Next, call the mask function for those items you wish to have masked.

jQuery(function($){   $("#date").mask("99/99/9999");   $("#phone").mask("(999) 999-9999");   $("#tin").mask("99-9999999");   $("#ssn").mask("999-99-9999");});

Optionally, if you are not satisfied with the underscore (‘_’) character as a placeholder, you may pass an optional argument to the maskedinput method.

jQuery(function($){   $("#product").mask("99/99/9999",{placeholder:" "});});

Optionally, if you would like to execute a function once the mask has been completed, you can specify that function as an optional argument to the maskedinput method.

jQuery(function($){   $("#product").mask("99/99/9999",{completed:function(){alert("You typed the following: "+this.val());}});});

Optionally, if you would like to disable the automatic discarding of the uncomplete input, you may pass an optional argument to the maskedinput method

jQuery(function($){   $("#product").mask("99/99/9999",{autoclear: false});});

You can now supply your own mask definitions.

jQuery(function($){   $.mask.definitions='';   $("#eyescript").mask("~9.99 ~9.99 999");});

You can have part of your mask be optional. Anything listed after ‘?’ within the mask is considered optional user input. The common example for this is phone number + optional extension.

jQuery(function($){   $("#phone").mask("(999) 999-9999? x99999");});

If your requirements aren’t met by the predefined placeholders, you can always add your own. For example, maybe you need a mask to only allow hexadecimal characters. You can add your own definition for a placeholder, say ‘h’, like so: Then you can use that to mask for something like css colors in hex with a .

jQuery(function($){   $("#phone").mask("#hhhhhh");});

By design, this plugin will reject input which doesn’t complete the mask. You can bypass this by using a ‘?’ character at the position where you would like to consider input optional. For example, a mask of «(999) 999-9999? x99999» would require only the first 10 digits of a phone number with extension being optional.

Supported markup options

data-inputmask attribute

You can also apply an inputmask by using the data-inputmask attribute. In the attribute you specify the options wanted for the inputmask. This gets parsed with $.parseJSON (for the moment), so be sure to use a well-formed json-string without the {}.

<input data-inputmask="'alias': 'date'" />
<input data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false" />
$(document).ready(function(){
  $(":input").inputmask();
});

data-inputmask-<option> attribute

All options can also be passed through data-attributes.

<input data-inputmask-mask="9" data-inputmask-repeat="10" data-inputmask-greedy="false" />
$(document).ready(function(){
  $(":input").inputmask();
});

Define custom definitions

You can define your own definitions to use in your mask.Start by choosing a masksymbol.

Next define your validator. The validator can be a regular expression or a function.

The return value of a validator can be true, false or a command object.

  • pos : position to insert

  • c : character to insert

  • caret : position of the caret

  • remove : position(s) to remove

    pos or

  • insert : position(s) to add :

    • { pos : position to insert, c : character to insert }
  • refreshFromBuffer :

    • true => refresh validPositions from the complete buffer
    • { start: , end: } => refresh from start to end

Cardinality specifies how many characters are represented and validated for the definition.

The prevalidator option is used to validate the characters before the definition cardinality is reached. (see ‘j’ example)

When you insert or delete characters, they are only shifted when the definition type is the same. This behavior can be overridden by giving a definitionSymbol. (see example x, y, z, which can be used for ip-address masking, the validation is different, but it is allowed to shift the characters between the definitions)

Inputmask.extendDefinitions({'f'{"validator""[0-9\(\)\.\+/ ]","cardinality"1,'prevalidator'null},'g'{"validator"function(chrs,buffer,pos,strict,opts){}"cardinality"1,'prevalidator'null},'j'{    validator"(19|20)\\d{2}",    cardinality4,    prevalidator{ validator"", cardinality1},{ validator"(19|20)", cardinality2},{ validator"(19|20)\\d", cardinality3}},'x'{    validator"",    cardinality1,    definitionSymbol"i"},'y'{validatorfunction(chrs,buffer,pos,strict,opts){var valExp2 =newRegExp("2|");returnvalExp2.test(bufferpos -1+ chrs);},    cardinality1,    definitionSymbol"i"},'z'{validatorfunction(chrs,buffer,pos,strict,opts){var valExp3 =newRegExp("25|2|");returnvalExp3.test(bufferpos -2+ bufferpos -1+ chrs);},    cardinality1,    definitionSymbol"i"}});

Specify a placeholder for a definition.

Defaults can be set as below.

Inputmask.extendDefaults({'autoUnmask'true});Inputmask.extendDefinitions({'A'{    validator"[A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5",    cardinality1,    casing"upper"},'+'{    validator"[0-9A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5",    cardinality1,    casing"upper"}});Inputmask.extendAliases({'Regex'{    mask"r",    greedyfalse,...}});

But if the property is defined within an alias you need to set it for the alias definition.

Inputmask.extendAliases({'numeric'{    allowPlusfalse,    allowMinusfalse}});

However, the preferred way to alter properties for an alias is by creating a new alias which inherits from the default alias definition.

Inputmask.extendAliases({'myNum'{    alias"numeric",    placeholder'',    allowPlusfalse,    allowMinusfalse}});

Once defined, you can call the alias by:

$(selector).inputmask("myNum");

All callbacks are implemented as options. This means that you can set general implementations for the callbacks by setting a default.

Inputmask.extendDefaults({onKeyValidationfunction(key,result){if(!result){alert('Your input is not valid')}}});

Smart Forms with jQuery Html5 & CSS3

March 28, 2014 | Ajax, Calendar, CSS2 / CSS3.0, Forms, HTML5, Premium


Smart Forms is a responsive professional Form Framework / pack with a clean consistent Form UI. The framework includes a variety of form Widgets such as Datepickers, Timepickers, Monthpickers, Colorpickers, Numeric Steppers, UI Sliders, Google maps, toggle switches validation, masking among other features.

Features:

  • Multiple form inputs
  • File inputs / uploaders
  • CSS3 checkboxes + Radios
  • CSS3 toggle switches
  • CSS3 review & rating
  • Tooltips + vector icons
  • Notification alerts
  • CSS3 multi shape buttons
  • Animated progress bars
  • Simple pricing tables
  • Ajax form processing
  • Input masking
  • PHP CAPTCHA with refresh support
  • 40+ starter templates included
  • Date & time picker widgets

Methods:

mask(elems)

Create a mask for the input.

$(selector).inputmask({ mask: "99-999-99"});

or

Inputmask({ mask: "99-999-99"}).mask(document.querySelectorAll(selector));

or

Inputmask("99-999-99").mask(document.querySelectorAll(selector));

or

var im = new Inputmask("99-999-99");
im.mask(document.querySelectorAll(selector));

or

Inputmask("99-999-99").mask(selector);

unmaskedvalue

Get the

$(selector).inputmask('unmaskedvalue');

or

var input = document.getElementById(selector);
if (input.inputmask)
  input.inputmask.unmaskedvalue()

Value unmasking

Unmask a given value against the mask.

var unformattedDate = Inputmask.unmask("23/03/1973", { alias: "dd/mm/yyyy"}); //23031973

remove

Remove the .

$(selector).inputmask('remove');

or

var input = document.getElementById(selector);
if (input.inputmask)
  input.inputmask.remove()

or

Inputmask.remove(document.getElementById(selector));

getemptymask

return the default (empty) mask value

$(document).ready(function(){
  $("#test").inputmask("999-AAA");
  var initialValue = $("#test").inputmask("getemptymask");  // initialValue  => "___-___"
});

hasMaskedValue

Check whether the returned value is masked or not; currently only works reliably when using jquery.val fn to retrieve the value

$(document).ready(function(){
  function validateMaskedValue(val){}
  function validateValue(val){}

  var val = $("#test").val();
  if ($("#test").inputmask("hasMaskedValue"))
    validateMaskedValue(val);
  else
    validateValue(val);
});

isComplete

Verify whether the current value is complete or not.

$(document).ready(function(){
  if ($(selector).inputmask("isComplete")){
    //do something
  }
});

getmetadata

The metadata of the actual mask provided in the mask definitions can be obtained by calling getmetadata. If only a mask is provided the mask definition will be returned by the getmetadata.

$(selector).inputmask("getmetadata");

setvalue

The setvalue functionality is to set a value to the inputmask like you would do with jQuery.val, BUT it will trigger the internal event used by the inputmask always, whatever the case. This is particular usefull when cloning an inputmask with jQuery.clone. Cloning an inputmask is not a fully functional clone. On the first event (mouseenter, focus, …) the inputmask can detect if it where cloned an can reactivate the masking. However when setting the value with jQuery.val there is none of the events triggered in that case. The setvalue functionality does this for you.

option(options, noremask)

Get or set an option on an existing inputmask. The option method is intented for adding extra options like callbacks, etc at a later time to the mask.

When extra options are set the mask is automatically reapplied, unless you pas true for the noremask argument.

Set an option

document.querySelector("#CellPhone").inputmask.option({
  onBeforePaste: function (pastedValue, opts) {
    return phoneNumOnPaste(pastedValue, opts);
  }
});
$("#CellPhone").inputmask("option", {
  onBeforePaste: function (pastedValue, opts) {
    return phoneNumOnPaste(pastedValue, opts);
  }
})

format

Instead of masking an input element it is also possible to use the inputmask for formatting given values. Think of formatting values to show in jqGrid or on other elements then inputs.

var formattedDate = Inputmask.format("2331973", { alias: "dd/mm/yyyy"});
var isValid = Inputmask.isValid("23/03/1973", { alias: "dd/mm/yyyy"});

numeric extensions

$(document).ready(function(){
   $(selector).inputmask("decimal");
   $(selector).inputmask("decimal", { allowMinus: false });
   $(selector).inputmask("integer");
});

Define the radixpoint

$(document).ready(function(){
   $(selector).inputmask("decimal", { radixPoint: "," });
});

Define the number of digits after the radixpoint

$(document).ready(function(){
   $(selector).inputmask("decimal", { digits: 3 });
});

When TAB out of the input the digits autocomplate with 0 if the digits option is given a valid number.

Grouping support through: autoGroup, groupSeparator, groupSize

$(document).ready(function(){
   $(selector).inputmask("decimal", { radixPoint: ",", autoGroup: true, groupSeparator: ".", groupSize: 3 });
});

Allow minus and/or plus symbol

$(document).ready(function(){
   $(selector).inputmask("decimal", { allowMinus: false });
   $(selector).inputmask("integer", { allowMinus: false, allowPlus: true });
});

Usage:

Include the js-files which you can find in the dist-folder. You have the bundled file which contains the main plugin code and also all extensions (date, numerics, other) or if you prefer to only include some parts, use the separate js-files in the dist/min folder.

If you use a module loader like requireJS, use the js-files in dist/inputmask

The minimum to include is the jquery.inputmask.js

<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.inputmask.js" type="text/javascript"></script>

Define your masks:

$(document).ready(function(){
   $(selector).inputmask("99-9999999");  //static mask
   $(selector).inputmask("mask", {"mask": "(999) 999-9999"}); //specifying fn & options
   $(selector).inputmask({"mask": "99-9999999"}); //specifying options only
   $(selector).inputmask("9-a{1,3}9{1,3}"); //mask with dynamic syntax 
});

or via data-inputmask attribute

<input data-inputmask="'alias': 'date'" />
<input data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false" />
<input data-inputmask="'mask': '99-9999999'" />
$(document).ready(function(){
    $(":input").inputmask();
});

Any option can also be passed through the use of a data attribute. Use data-inputmask-<the name op the option>=»value»

<input id="example1" data-inputmask-clearmaskonlostfocus="false" />
<input id="example2" data-inputmask-regex="[a-za-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:(?:*)?\.)+(?:*)?" />
$(document).ready(function(){
   $("#example1").inputmask("99-9999999");
   $("#example2").inputmask("Regex");
});

Allowed HTML-elements

  • input type=»text»
  • input type=»tel»
  • div contenteditable=»true» (and all others supported by contenteditable)
  • any html-element (mask text content or set maskedvalue with jQuery.val)

Default masking definitions

  • 9 : numeric
  • a : alphabetical

There are more definitions defined within the extensions. You can find info within the js-files or by further exploring the options.

Usage:


Include the js-files which you can find in the folder.

via Inputmask class

<script src="jquery.js"></script>
<script src="inputmask.js"></script>
<script src="inputmask.???.Extensions.js"></script>
var selector = document.getElementById("selector");

var im = new Inputmask("99-9999999");
im.mask(selector);

Inputmask({"mask": "(999) 999-9999", .... other options .....}).mask(selector);
Inputmask("9-a{1,3}9{1,3}").mask(selector);
Inputmask("9", { repeat: 10 }).mask(selector);

via jquery plugin

<script src="jquery.js"></script>
<script src="inputmask.js"></script>
<script src="inputmask.???.Extensions.js"></script>
<script src="jquery.inputmask.js"></script>

or with the bundled version

<script src="jquery.js"></script>
<script src="jquery.inputmask.bundle.js"></script>
$(document).ready(function(){
  $(selector).inputmask("99-9999999");  //static mask
  $(selector).inputmask({"mask": "(999) 999-9999"}); //specifying options
  $(selector).inputmask("9-a{1,3}9{1,3}"); //mask with dynamic syntax
});

via data-inputmask attribute

<input data-inputmask="'alias': 'date'" />
<input data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false" />
<input data-inputmask="'mask': '99-9999999'" />
$(document).ready(function(){
  $(":input").inputmask();
  or
  Inputmask().mask(document.querySelectorAll("input"));
});

Any option can also be passed through the use of a data attribute. Use data-inputmask-<the name of the option>=»value»

<input id="example1" data-inputmask-clearmaskonlostfocus="false" />
<input id="example2" data-inputmask-regex="[a-za-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:(?:*)?\.)+(?:*)?" />
$(document).ready(function(){
  $("#example1").inputmask("99-9999999");
  $("#example2").inputmask("Regex");
});

If you like to automatically bind the inputmask to the inputs marked with the data-inputmask- … attributes you may also want to include the inputmask.binding.js

...
<script src="inputmask.binding.js"></script>
...

If you use a module loader like requireJS

Add in your config.js

paths: {
  ...
  "inputmask.dependencyLib": "../dist/inputmask/inputmask.dependencyLib.jquery",
  "inputmask": "../dist/inputmask/inputmask",
  ...
}

As dependencyLib you can choose between the supported libraries.

  • inputmask.dependencyLib (vanilla)
  • inputmask.dependencyLib.jquery
  • inputmask.dependencyLib.jqlite
  • …. (others are welcome)

Allowed HTML-elements

  • (and all others supported by contenteditable)
  • any html-element (mask text content or set maskedvalue with jQuery.val)

Default masking definitions

  • : numeric
  • : alphabetical
  • : alphanumeric

There are more definitions defined within the extensions.You can find info within the js-files or by further exploring the options.

Usage:

Include the js-files which you can find in the dist-folder. You have the bundled file which contains the main plugin code and also all extensions. (date, numerics, other) or if you prefer to only include some parts, use the separate js-files in the dist/min folder.

The minimum to include is the jquery.inputmask.js

<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.inputmask.js" type="text/javascript"></script>

Define your masks:

$(document).ready(function(){
   $("#date").inputmask("d/m/y");  //direct mask
   $("#phone").inputmask("mask", {"mask": "(999) 999-9999"}); //specifying fn & options
   $("#tin").inputmask({"mask": "99-9999999"}); //specifying options only
});

or

<input data-inputmask="'alias': 'date'" />
<input data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false" />
<input data-inputmask="'mask': '99-9999999'" />
$(document).ready(function(){
    $(":input").inputmask();
});

Default masking definitions

  • 9 : numeric
  • a : alphabetic

There are more definitions defined within the extensions. You can find info within the js-files or by further exploring the options.

Supported markup options

data-inputmask attribute

You can also apply an inputmask by using the data-inputmask attribute. In the attribute you specify the options wanted for the inputmask. This gets parsed with $.parseJSON (for the moment), so be sure to use a well-formed json-string without the {}.

<input data-inputmask="'alias': 'date'" />
<input data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false" />
$(document).ready(function(){
  $(":input").inputmask();
});

data-inputmask-<option> attribute

All options can also be passed through data-attributes.

<input data-inputmask-mask="9" data-inputmask-repeat="10" data-inputmask-greedy="false" />
$(document).ready(function(){
  $(":input").inputmask();
});

Define custom definitions

You can define your own definitions to use in your mask. Start by choosing a masksymbol.

validator(chrs, maskset, pos, strict, opts)

Next define your validator. The validator can be a regular expression or a function.

The return value of a validator can be true, false or a command object.

Options of the command object
  • pos : position to insert
  • c : character to insert
  • caret : position of the caret
  • remove : position to remove
  • refreshFromBuffer :
    • true => refresh validPositions from the complete buffer
    • { start: , end: } => refresh from start to end
prevalidator(chrs, maskset, pos, strict, opts)

The prevalidator option is used to validate the characters before the definition cardinality is reached. (see ‘j’ example)

definitionSymbol

When you insert or delete characters, they are only shifted when the definition type is the same. This behavior can be overridden by giving a definitionSymbol. (see example x, y, z, which can be used for ip-address masking, the validation is different, but it is allowed to shift the characters between the definitions)

$.extend($.inputmask.defaults.definitions, {
    'f': {  //masksymbol
        "validator": "[0-9\(\)\.\+/ ]",
        "cardinality": 1,
        'prevalidator': null
    },
	'g': {
        "validator": function (chrs, buffer, pos, strict, opts) { 
			//do some logic and return true, false, or { "pos": new position, "c": character to place }
		}		
        "cardinality": 1,
        'prevalidator': null
    },
	'j': { //basic year
            validator: "(19|20)\\d{2}",
            cardinality: 4,
            prevalidator: 
                        { validator: "", cardinality: 1 },
                        { validator: "(19|20)", cardinality: 2 },
                        { validator: "(19|20)\\d", cardinality: 3 }
            
     }, 
	 'x': {
        validator: "",
        cardinality: 1,
        definitionSymbol: "i" //this allows shifting values from other definitions, with the same masksymbol or definitionSymbol
     },
     'y': {
        validator: function (chrs, buffer, pos, strict, opts) {
                        var valExp2 = new RegExp("2|");
                        return valExp2.test(bufferpos - 1 + chrs);
                    },
        cardinality: 1,
        definitionSymbol: "i"
     },
     'z': {
        validator: function (chrs, buffer, pos, strict, opts) {
                       var valExp3 = new RegExp("25|2|");
                        return valExp3.test(bufferpos - 2 + bufferpos - 1 + chrs);
        },
        cardinality: 1,
        definitionSymbol: "i"
      }
});

Specify a placeholder for a definition.

$.extend($.inputmask.defaults, {
    'autoUnmask': true
});

General

set a value and apply mask

this can be done with the traditional jquery.val function (all browsers) or JavaScript value property for browsers which implement lookupGetter or getOwnPropertyDescriptor

$(document).ready(function(){
  $("#number").val(12345);

  var number = document.getElementById("number");
  number.value = 12345;
});

with the autoUnmaskoption you can change the return of $.fn.val (or value property) to unmaskedvalue or the maskedvalue

$(document).ready(function(){
  $('#<%= tbDate.ClientID%>').inputmask({ "mask": "d/m/y", 'autoUnmask' : true});    //  value: 23/03/1973
  alert($('#<%= tbDate.ClientID%>').val());    // shows 23031973     (autoUnmask: true)

  var tbDate = document.getElementById("<%= tbDate.ClientID%>");
  alert(tbDate.value);    // shows 23031973     (autoUnmask: true)
});

auto-casing inputmask

You can define within a definition to automatically apply some casing on the entry in an input by giving the casing.Casing can be null, «upper», «lower» or «title».

Inputmask.extendDefinitions({
  'A': {
    validator: "",
    cardinality: 1,
    casing: "upper" //auto uppercasing
  },
  '+': {
    validator: "",
    cardinality: 1,
    casing: "upper"
  }
});

Include jquery.inputmask.extensions.js for using the A and # definitions.

$(document).ready(function(){
  $("#test").inputmask("999-AAA");    //   => 123abc ===> 123-ABC
});

Usage:

Include the js-files which you can find in the folder.

via Inputmask class

<scriptsrc="jquery.js"><script><scriptsrc="inputmask.js"><script><scriptsrc="inputmask.???.Extensions.js"><script>
var selector =document.getElementById("selector");var im =newInputmask("99-9999999");im.mask(selector);Inputmask({"mask""(999) 999-9999",....other options .....}).mask(selector);Inputmask("9-a{1,3}9{1,3}").mask(selector);Inputmask("9",{ repeat10}).mask(selector);

via jquery plugin

<scriptsrc="jquery.js"><script><scriptsrc="inputmask.js"><script><scriptsrc="inputmask.???.Extensions.js"><script><scriptsrc="jquery.inputmask.js"><script>

or with the bundled version

<scriptsrc="jquery.js"><script><scriptsrc="jquery.inputmask.bundle.js"><script>
$(document).ready(function(){$(selector).inputmask("99-9999999");$(selector).inputmask({"mask""(999) 999-9999"});$(selector).inputmask("9-a{1,3}9{1,3}");});

via data-inputmask attribute

<inputdata-inputmask="'alias': 'date'" /><inputdata-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false" /><inputdata-inputmask="'mask': '99-9999999'" />
$(document).ready(function(){$(":input").inputmask();  orInputmask().mask(document.querySelectorAll("input"));});

Any option can also be passed through the use of a data attribute. Use data-inputmask-<the name of the option>=»value»

<inputid="example1"data-inputmask-clearmaskonlostfocus="false" /><inputid="example2"data-inputmask-regex="[a-za-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:(?:*)?\.)+(?:*)?" />
$(document).ready(function(){$("#example1").inputmask("99-9999999");$("#example2").inputmask("Regex");});

If you like to automatically bind the inputmask to the inputs marked with the data-inputmask- … attributes you may also want to include the inputmask.binding.js

...<scriptsrc="inputmask.binding.js"><script>...

If you use a module loader like requireJS


Have a look at the inputmask.loader.js for usage.

Example config.js

paths{..."inputmask.dependencyLib""../dist/inputmask/inputmask.dependencyLib","inputmask""../dist/inputmask/inputmask",...}

As dependencyLib you can choose between the supported libraries.

  • inputmask.dependencyLib (vanilla)
  • inputmask.dependencyLib.jquery
  • inputmask.dependencyLib.jqlite
  • …. (others are welcome)
  • (and all others supported by contenteditable)
  • any html-element (mask text content or set maskedvalue with jQuery.val)
  • : numeric
  • : alphabetical
  • : alphanumeric

There are more definitions defined within the extensions.You can find info within the js-files or by further exploring the options.

Masking types

Static masks

These are the very basic of masking. The mask is defined and will not change during the input.

$(document).ready(function(){
  $(selector).inputmask("aa-9999");  //static mask
  $(selector).inputmask({mask: "aa-9999"});  //static mask
});

Optional masks

It is possible to define some parts in the mask as optional. This is done by using .

Example:

$('#test').inputmask('(99) 9999-9999');

This mask wil allow input like or .

Input => 12123451234 mask => (12) 12345-1234 (trigger complete) Input => 121234-1234 mask => (12) 1234-1234 (trigger complete) Input => 1212341234 mask => (12) 12341-234_ (trigger incomplete)

skipOptionalPartCharacter

As an extra there is another configurable character which is used to skip an optional part in the mask.

skipOptionalPartCharacter: " "

Input => 121234 1234 mask => (12) 1234-1234 (trigger complete)

When is set in the options (default), the mask will clear out the optional part when it is not filled in and this only in case the optional part is at the end of the mask.

For example, given:

$('#test').inputmask('999');

While the field has focus and is blank, users will see the full mask . When the required part of the mask is filled and the field loses focus, the user will see . When both the required and optional parts of the mask are filled out and the field loses focus, the user will see .

Optional masks with greedy false

When defining an optional mask together with the greedy: false option, the inputmask will show the smallest possible mask as input first.

$(selector).inputmask({ mask: "9", greedy: false });

The initial mask shown will be «_» instead of «_-____».

Dynamic masks

Dynamic masks can change during the input. To define a dynamic part use { }.

{n} => n repeats{n,m} => from n to m repeats

Also {+} and {*} is allowed. + start from 1 and * start from 0.

$(document).ready(function(){
  $(selector).inputmask("aa-9{4}");  //static mask with dynamic syntax
  $(selector).inputmask("aa-9{1,4}");  //dynamic mask ~ the 9 def can be occur 1 to 4 times

  //email mask
  $(selector).inputmask({
    mask: "*{1,20}@*{1,20}",
    greedy: false,
    onBeforePaste: function (pastedValue, opts) {
      pastedValue = pastedValue.toLowerCase();
      return pastedValue.replace("mailto:", "");
    },
    definitions: {
      '*': {
        validator: "[0-9A-Za-z!#$%&'*+/=?^_`{|}~\-]",
        cardinality: 1,
        casing: "lower"
      }
    }
  });
});

Alternator masks

The alternator syntax is like an OR statement. The mask can be one of the 2 choices specified in the alternator.

To define an alternator use the |.ex: «a|9» => a or 9 «(aaa)|(999)» => aaa or 999

Also make sure to read about the keepStatic option.

$("selector").inputmask("(99.9)|(X)", {
  definitions: {
    "X": {
      validator: "",
      cardinality: 1,
      casing: "upper"
    }
  }
});

or

$("selector").inputmask({
  mask: "99.9", "X",
  definitions: {
    "X": {
      validator: "",
      cardinality: 1,
      casing: "upper"
    }
  }
});

Preprocessing masks

You can define the mask as a function which can allow to preprocess the resulting mask. Example sorting for multiple masks or retrieving mask definitions dynamically through ajax. The preprocessing fn should return a valid mask definition.

$(selector).inputmask({ mask: function () { /* do stuff */ return "AAA-999", "999-AAA"; }});

JIT Masking

Just in time masking. With the jitMasking option you can enable jit masking. The mask will only be visible for the user entered characters. Default: false

Value can be true or a threshold number or false.

Inputmask("date", { jitMasking: true }).mask(selector);

date & datetime extensions

$(document).ready(function(){
   $(selector).inputmask("dd/mm/yyyy");
   $(selector).inputmask("mm/dd/yyyy");
   $(selector).inputmask("date"); // alias for dd/mm/yyyy
   $(selector).inputmask("date", {yearrange: { minyear: 1900, maxyear: 2099 }}); //specify year range
});

The date aliases take leap years into account. There is also autocompletion on day, month, year. For example:

input: 2/2/2012 result: 02/02/2012 input: 352012 result: 03/05/2012 input: 3/530 result: 03/05/2030 input: ctrl rightarrow result: the date from today

$(document).ready(function(){
   $(selector).inputmask("datetime"); // 24h
   $(selector).inputmask("datetime12"); // am/pm
});

.NET Nuget Package Install

PM> Install-Package jQuery.InputMask

In App_Start, BundleConfig.cs

bundles.Add(new ScriptBundle("~/bundles/inputmask").Include(
                        "~/Scripts/jquery.inputmask/jquery.inputmask-{version}.js",
						"~/Scripts/jquery.inputmask/jquery.inputmask.extensions-{version}.js",
						"~/Scripts/jquery.inputmask/jquery.inputmask.date.extensions-{version}.js",
						"~/Scripts/jquery.inputmask/jquery.inputmask.numeric.extensions-{version}.js"));

In Layout

@Scripts.Render("~/bundles/inputmask")

#=========== TODO ===========

getemptymask command

return the default (empty) mask value

$(document).ready(function(){
   $("#test").inputmask("999-AAA");
   var initialValue = $("#test").inputmask("getemptymask");  // initialValue  => "___-___"
});

onKeyUp / onKeyDown option

Use this to do some extra processing of the input when certain keys are pressed. This can be usefull when implementing an alias, ex. decimal alias, autofill the digits when pressing tab.

see jquery.inputmask.extensions.js for some examples

onBeforePaste

This callback allows for preprocessing the pasted value before actually handling the value for masking. This can be usefull for stripping away some characters before processing.

$(document).ready(function(){
   $("#test").inputmask("99.", {
                repeat: 4,
                onBeforePaste: function (pastedValue) {
                    //do somehing with the value
                    return pastedValue;
                }
            });
});

onBeforeMask

This callback allows for preprocessing the initial value before actually handling the value for masking. This can be usefull for stripping away some characters before processing.

$(document).ready(function(){
   $("#test").inputmask("99.", {
                repeat: 4,
                onBeforeMask: function (initialValue) {
                    //do somehing with the value
                    return initialValue;
                }
            });
});

hasMaskedValue

Check whether the returned value is masked or not; currently only works reliably when using jquery.val fn to retrieve the value

$(document).ready(function(){
	function validateMaskedValue(val){}
	function validateValue(val){}

	var val = $("#test").val();
    if($("#test").inputmask("hasMaskedValue"))
	  validateMaskedValue(val); 
   else validateValue(val); 
});

С этим читают