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

Methods:

mask

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. The setvalue functionality does this for you.

option

Get or set an option on an existing inputmask.

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

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"});

Применение:

Подключите JS файлы, которые вы можете найти в папке .

с помощью класса Inputmask

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

с помощью jquery плагина

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

или с помощью входящей в комлект поставки версии

<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
});

с помощью data-inputmask атрибута

<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"));
});

Любая опция также может быть передана через использование data-атрибута. Используйте data-inputmask-<имя опции>=»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");
});

Если вы хотите автоматически привязать маску ввода для отметки ввода с data-inputmask- … атрибутами, вы можете включить inputmask.binding.js

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

Если вы используете модуль загрузки requireJS

Добавьте в ваш config.js

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

Библиотеки зависимостей вы можете выбрать между поддерживаемыми библиотеками.

  • inputmask.dependencyLib (vanilla)
  • inputmask.dependencyLib.jquery
  • inputmask.dependencyLib.jqlite
  • …. (другие приветствуются)

Разрешенные HTML-элементы

  • (и все остальные при поддержке contenteditable)
  • любой html-элемент (текстовое содержимое маски или установка значения маски с jQuery.val)

Символы для маски по умолчанию

  • : цифры
  • : буквы алфавита
  • : буквы и цифры

Есть несколько символов для маски ввода, определенных в ваших расширениях.Вы можете найти информацию в JS-файлах или путем дальнейшего изучения опций.

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

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
});

Маски ввода в access примеры

Сведения о типах данных, полей и их свойствах являются в Access 2002 базовыми и используются при создании таблицы в режиме конструктора.

Свойство Маска ввода

Если щелкнуть в ее пределах (см. рис. 3.10), можно будет вводить значения вручную. Вначале введем значение 0L → L в строку Маска ввода. Начиная со следующей вводимой записи и до тех пор, пока маска ввода не будет снова изменена, коды стран будут задаваться в том виде, который показан на рис. 3.11 для кодов Индии и Пакистана. Это происходит в соответствии с правилами настройки форматов, приведенными выше (раздел «Свойства полей»). (Мы не обсуждаем сейчас вопрос о смысле такой установки, а просто рассматриваем возможности маски ввода.)

Правда, при переходе из режима конструктора в режим просмотра таблицы (см. рис. 3.10 и 3.11) Access 2002 может предупредить пользователя о возможных опасностях, выдав информацию о том, что условия целостности данных изменены и информация может противоречить новым условиям, предложив при этом проверить существующие данные в новых условиях. Если подобное предложение поступит, то с ним имеет смысл согласиться и ответить Да. Для выбора значений маски ввода может также использоваться мастер маски ввода. Если вы захотите воспользоваться его помощью и щелкнете по кнопке

После того как вы согласитесь с этим предложением (в случае несогласия вы никуда не продвинетесь), появится окно мастера маски ввода (см. рис. 3.12). Открывшееся окно предлагает вам выбрать Маску ввода в соответствии с заданным свойством Формат данных. Чтобы проверить работу маски ввода, можете ввести данные в поле Проба. Значения свойства Маска ввода для ввода вручную рассматривались выше. Здесь мы перечислим шаблоны для случая их задания мастером: • Общий формат даты; • Длинный формат даты; • Средний формат даты; • Короткий формат даты; • Длинный формат времени; • Средний формат времени; • Короткий формат времени. Чтобы изменить маску ввода, щелкните по кнопке Список. Теперь выберите в открывшемся поле какую-либо позицию, например Средний формат времени (рис. 3.12). Затем, щелкнув по кнопке Далее, вы перейдете в следующее окно мастера масок (см. рис. 3.14).

В этом окне вы также можете изменить шаблон. Это можно сделать в поле Маска ввода, которое в этом случае активизируется. Далее в том же окне мастера масок вы можете изменить вид заполнителей или меток. Эти метки заполняют пробелы между значащими символами. Выбор нужной метки из списка производится в поле Вид заполнителя с помощью стрелки прокрутки. Указанные вами метки вводятся автоматически по мере набора символов. Использовав все возможности коррекции масок, которыми располагает мастер, вы получите не менее разнообразные и экзотические маски, чем те, что пользователь создает вручную. Проверить, как введены данные, можно, указав их в поле проверки Проба и затем нажав клавишу Enter. После этого, если не последует возражений со стороны мастера, щелкните по кнопке Далее. В следующем окне (см. рис. 3.15) мастер масок предоставит вам еще одну возможность изменить маску для данного шаблона, задав ее значение и вид заполнителя.

Затем мастер поинтересуется, как вы хотите сохранить данные (рис. 3.16). Вы можете сохранить их либо вместе с возможными вспомогательными символами (они указываются во второй части маски, но являются необязательными), либо без них.

Когда вы дадите тот или иной ответ, щелкните по кнопке Готово, и маска будет сформирована. Если на этой стадии работы вы выберете опцию Далее, то сначала появится еще одно окно. В нем мастер масок сообщит вам, что теперь у него есть все необходимое для создания маски. На рис. 3.17 и 3.18 мы видим, как выглядит изменение маски ввода в окне конструктора и в окончательном виде в таблице Страны.

В нашем примере сформированная мастером маска будет работать с момента ее установки и до следующей корректировки. Все это время Access 2002 будет допускать ввод только тех записей, у которых код страны имеет четыре разряда. На рис. 3.18 показаны записи, введенные согласно заданным условиям.

Сравнивая два способа формирования маски ввода (вручную и с помощью мастера масок), мы пришли к заключению, что первый путь значительно проще, и поэтому именно он рекомендован пользователю.

Свойство Формат

Если теперь мы включим режим просмотра таблицы, которая была показана на рис. 3.18, то увидим что все строки в поле Страна заполнены прописными буквами (см. рис. 3.20). Кстати, это еще одно отличие свойства Формат от свойства Маска ввода: его установки влияют на все содержимое поля, независимо от времени его (содержимого) ввода.

InputMask options

A masking pattern must be provided and must contain at least one editable character, or an will be thrown.

The following format characters define editable parts of the mask:

  • — number
  • — letter
  • — letter, forced to upper case when entered
  • — alphanumeric
  • — alphanumeric, forced to upper case when entered

If you need to include one of these characters as a static part of the mask, you can escape them with a preceding backslash:

var mask =newInputMask({pattern'\\A11 \\1AA', value'A99 1ZZ'})mask.getValue()

If you need to include a static backslash in a pattern, you must escape it:

var mask =newInputMask({pattern'\\\\A11\\\\', value'Z98'})mask.getValue()

Otherwise, all other characters are treated as static parts of the pattern.

  • Credit card number:
  • Date:
  • ISO date:
  • Time:
  • Canadian postal code:
  • Norn Iron license plate:

An object defining additional custom format characters to use in the mask’s pattern.

When defining a new format character, a function is required and a function can optionally be defined to modify the validated character before adding it to the mask’s value.

For example this is how you would define as a new format character which accepts word character input (alphanumeric or underscore) and forces it to lower case when entered:

var mask =newInputMask({  pattern'Awwwww',  formatCharacters{'w'{validatefunction(char){return\w.test(char)}transformfunction(char){returnchar.toLowerCase()}}}})

To override a built-in format character, pass its character as a property of this object along with the new definition.

To disable a built-in format character, pass its character as a property of this object with a value:

var mask =newInputMask({  pattern'A1111',  formatCharacters{'A'null}})

The character which is used to fill in editable slots for which there is no input yet when getting the mask’s current value.

Defaults to ; must be a single character.

var mask =newInputMask({pattern'11/11/1111', placeholderChar''})mask.input('1')mask.getValue()

An optional initial value for the mask.

An optional default selection — defaults to , placing the cursor before the first character.

An optional property that, if true, progressively shows the mask as input is entered. Defaults to

Example:
Given an input with a mask of , a value of , and set to , then the input’s value is formatted as
Given the same input but with a value of , then the input’s value is formatted as
Given the same input but with a value of , then the input’s value is formatted as

Общие сведения о масках ввода

Маска ввода — это строка символов, указывающая формат допустимых значений входных данных. Маски ввода можно использовать в полях таблиц или запросов, а также в элементах управления форм и отчетов. Маска ввода хранится в свойствах объекта.

Маску ввода рекомендуется использовать, когда вводимые значения должны иметь единый формат, например для полей с номерами телефонов из десяти цифр. Если пользователь введет номер, не указав код города, данные не будут приняты в Access, пока пользователь не добавит код города.

Три компонента маски ввода

Маски ввода состоят из одного обязательного и двух необязательных компонентов, разделенных точками с запятой. Назначение каждого из компонентов описано ниже.

Первый компонент является обязательным. Он представляет собой знак или строку (последовательность знаков) маски с заполнителями и литералами, например круглыми скобками, точками и дефисами.

Второй компонент не является обязательным и определяет способ хранения встроенных знаков маски в поле. Если для этого компонента задано значение 0, знаки сохраняются вместе с данными, а если 1, то знаки отображаются без сохранения. Выбрав значение 1, можно сэкономить место для хранения базы данных.

Третий компонент маски ввода также не является обязательным и определяет знак, используемый в качестве заполнителя. По умолчанию в Access используется знак подчеркивания (_). Чтобы задать другой знак, введите его в третьем компоненте маски.

Пример маски ввода для телефонных номеров в формате России: (999) 000-00-00 ;0 ;-:

В маске используются два заполнителя — 9 и 0. Заполнитель 9 обозначает необязательные цифры (код города можно не вводить), а 0 — обязательные.

Значение 0 во втором компоненте маски ввода указывает на то, что знаки маски следует хранить вместе с данными.

Третий компонент маски ввода указывает на то, что вместо знака подчеркивания ( _) в качестве заполнителя будет использоваться дефис ( -).

Создание и использование полей подстановки

Подстановка в режиме конструктора таблиц

В результате на экране возникнет первое окно мастера подстановок (см. рис. 3.22). Мастер создает столбец подстановок, то есть список значений, из которых надо выбрать подходящее. В этом окне следует указать, что нужно вывести на экран: список значений из таблицы или список запроса, который пользователь сам будет заполнять по своему усмотрению.

Приняв решение, пользователь выбирает в диалоговом окне соответствующий переключатель, а затем щелкает по кнопке Далее. Если был выбран первый вариант, мастер подстановок открывает следующее диалоговое окно (см. рис. 3.23). Здесь пользователь определяет таблицу и/или запрос, значениями которых он будет заполнять поле подстановки. Например, на рис. 3.23 показано, что эти значения выбираются из таблицы Фирмы. Теперь снова надо щелкнуть по кнопке Далее. Если вы передумали и хотите что-либо исправить в предыдущем окне, вернитесь к нему с помощью кнопки Назад или вообще отмените все предыдущие действия, щелкнув по кнопке Отмена.

В следующем окне (см. рис. 3.24) вы должны определить объект-источник подстановки и указать те поля в этом объекте, из которых будут выбираться конкретные значения. Сначала пометьте их в левом поле с помощью кнопки с одной стрелкой, указывающей вправо (для каждого значения по отдельности), или с двумя стрелками (для всех сразу). Затем перенесите их в правое поле.

Теперь повторите те же операции с кнопками, что и в предыдущем окне. Если вы выбрали Далее, то в следующем окне мастера подстановок (см. рис. 3.25) к вашим услугам появится столбец. В нем содержится перечень значений, из которых следует выбрать нужное (в нашем случае это названия фирм). В окне есть опция, рекомендующая скрыть ключевые поля (рекомендуется). Мы согласны с разработчиками Access и также советуем поставить в этом поле флажок.

Если вас не устраивает ширина столбца и вы хотите ее изменить, мастер подстановок любезно порекомендует либо передвинуть мышью правую границу столбца, установив его желаемую ширину, либо дважды щелкнуть правой кнопкой мыши по заголовку столбца и задать его размер. Теперь щелкните по кнопке Готово, и процесс будет завершен. На экране появится окно с предложением сохранить созданную таблицу сейчас или позже (рис. 3.26), а на следующем рисунке (см. рис. 3.27) – и сама таблица, где следует нажать на стрелку прокрутки. В результате в поле Фирмы появится столбец значений, в котором можно выбрать нужную строку. Если же щелкнуть по кнопке Далее, то в конечном счете вы выйдете к той же таблице, но через две промежуточных стадии (на рисунках они не представлены). На первом этапе следует назвать таблицу или согласиться с предлагаемым именем (мы уже знаем, что это всегда Таблица с каким-либо номером). На втором этапе Access поинтересуется, хотите ли вы перед выводом на экран итоговой таблицы запомнить исходную.

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.

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

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.

InputMask editing methods

Editing methods will not allow the string being edited to contain invalid values according to the mask’s pattern.

Any time an editing method results in either the or the changing, it will return .

Otherwise, if an invalid (e.g. trying to input a letter where the pattern specifies a number) or meaningless (e.g. backspacing when the cursor is at the start of the string) editing operation is attempted, it will return .

Applies a single character of input based on the current selection.

  • If a text selection has been made, editable characters within the selection will be blanked out, the cursor will be moved to the start of the selection and input will proceed as below.

  • If the cursor is positioned before an editable character and the input is valid, the input will be added. The cursor will then be advanced to the next editable character in the mask.

  • If the cursor is positioned before a static part of the mask, the cursor will be advanced to the next editable character.

After input has been added, the cursor will be advanced to the next editable character position.

Performs a backspace operation based on the current selection.

  • If a text selection has been made, editable characters within the selection will be blanked out and the cursor will be placed at the start of the selection.

  • If the cursor is positioned after an editable character, that character will be blanked out and the cursor will be placed before it.

  • If the cursor is positioned after a static part of the mask, the cursor will be placed before it.

Applies a string of input based on the current selection.

This behaves the same as — and is effectively like — calling for each character in the given string with one key difference — if any character within the input is determined to be invalid, the entire paste operation fails and the mask’s value and selection are unaffected.

Pasted input may optionally contain static parts of the mask’s pattern.

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. 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"});

Sorting masks of input which are allowed

To select a mask of input which matches to a phone number more than others a list of all possible masks has to be sorted in a special way. During a thinking of rules were accepted the following definitions:

  1. All symbols in a mask were segmented into 2 types: significant symbols (in my case it is the symbol which matches any digit, and digits ) and symbols-decorators (all others).

  2. Another segmentation of symbols in a mask of input is templated symbols (in my case it is a symbol ) and others.

As a result the following rules of sorting in the order of applying were written:

  1. When comparing 2 masks of input per symbols only significant symbols (not decorators) is taken into account.

  2. Different templated symbols are taken as equivalents, another significant symbols are compared based on their codes.

  3. Non-templated symbols are always less than templated one and they located above in a result.

  4. The shorter a length of significant characters in a mask of input, the mask of input is smaller and is located above in a result.

Quick Start

Include .

<script src="path/js/masking-input.js" data-autoinit="true"></script>`

Add either the css file to your page, or incorporate the .scss component into your sass build

<link rel="stylesheet" href="path/css/masking-input.css"/>

Add inputs with , and attributes with the class of . Include when requiring numbers only.

	 <label for="zip">Zip Code</label>
  	 <input id="zip" type="tel" placeholder="XXXXX" pattern="\d{5}" 
  	     class="masked" name="uszipcode" title="5-digit zip code"> 

If your placeholder includes non-digits and non-letters, no worries. They’ll be added by the script. Your mobile users won’t have to change their touch keyboards. They simply need to enter letters.

Do make sure that your placeholder would match the regular expression of your pattern if all the X’s were converted to integers.

If your regular expressions include letters, you must include the made up attribute. Similar to the pattern, include an for each number and an underscore for each required letter.

	<label for="zipca">Canadian Zip Code</label>
  	<input placeholder="XXX XXX" pattern="\w\d\w \d\w\d" class="masked" 
  		data-charset="_X_ X_X" id="zipca" type="text" name="zipcodeca" 
  	    title="6-character alphanumeric zip code in the format of A1A 1A1">

If the digits allowed by your regular expression are constrained or complicated, such as months only allowing 01-12, include a made up attribute that takes as its value a valid value that would match the pattern.

	<label for="expiration"> Credit Card Expiration </label>
    <input id="expiration" type="tel" placeholder="MM/YY" class="masked" 
    	pattern="(1|0)\/(1|2\d)" 
    	data-valid-example="05/18"> 

Exceptions

Complex Regular Expressions

If the digits allowed by your regular expression are constrained or complicated, such as months only allowing 01-12, include a made up attribute that takes as its value a valid value that would match the pattern.

	<label for="expiration"> Credit Card Expiration </label>
    <input id="expiration" type="tel" placeholder="MM/YY" class="masked" 
    	pattern="(1|0)\/(1|2\d)" 
    	data-valid-example="11/18"
    	title="2-digit month and 2-digit year greater than 01/15"> 

I’ve taken care of MM in , because that is common. If you have exceptions, add the exceptions there. If you need an expiration month, it is best to use instead.

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 (99) 99999-9999 or (99) 9999-9999.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: "99999", 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"; }});
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector