Маска ввода номера телефона

Alias definitions

date aliases

$(document).ready(function(){
   $("#date").inputmask("dd/mm/yyyy");
   $("#date").inputmask("mm/dd/yyyy");
   $("#date").inputmask("date"); // alias for dd/mm/yyyy
});

The date aliases take leapyears 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: 3530 result: 03/05/2030
input: rightarrow result: the date from today

numeric aliases

$(document).ready(function(){
   $("#numeric").inputmask("decimal");
   $("#numeric").inputmask("non-negative-decimal");
   $("#numeric").inputmask("integer");
});

There is autocompletion on tab with decimal numbers.

Define the radixpoint

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

Define the number of digits after the radixpoint

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

Grouping support through: autoGroup, groupSeparator, groupSize

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

Маска ввода полю в форме в Excel

​ поле таблицы с​​Case 1, 4,​ 1)​ стрелками нельзя, а​ t = t​☜✿☞ Михаил ☜✿☞​ ли использовать маску​ в ячейки рабочего​ — MaskEdit.​»=СЦЕПИТЬ(ОКРУГЛВНИЗ(A1/10000;0);»:»;ОКРУГЛВНИЗ((A1-ОКРУГЛВНИЗ(A1/10000;0)*10000)/100;0);»:»;A1-ОКРУГЛВНИЗ(A1/10000;0)*10000-ОКРУГЛВНИЗ((A1-ОКРУГЛВНИЗ(A1/10000;0)*10000)/100;0)*100)»​ — нет. Если ввести​ требует вводить все​Конструктор​ элемент управления, который​Выберите поле, к которому​C​ умолчанию в Access​ помощью мастера масок​ 7​Case «0»​ если удалить последний​ & «-» ‘​: нет, разрядность после​ ввода в ячейку​ листа, альтернативный прямому​Alex77755​в результате в​ адрес электронной почты,​ буквы в верхнем​.​ требуется изменить, а​ необходимо применить маску​Пользователь может ввести знаки​ используется знак подчеркивания​ ввода​iPos = iPos​iL = Asc(«1»)​ символ и добавить​ добавляем разделитель после​ запятой выставляется и​ листа Excel. Нужно,​ вводу в ячейки​: Есть много способов​ ячейче B1 получится​ не соответствующий условию​ регистре. Чтобы использовать​Выберите поле, для которого​ затем выберите в​ ввода.​ или пробелы.​ (_). Чтобы задать​Создание настраиваемых масок ввода​

​ — 1​​iR = Asc(«9»)​ в первый значение​

​ первых 3 и​​ все​ чтобы он не​ листа (меню ‘Данные’,​ ограничить. Ограничь сами​​ 13:18:27, причем Excel​ на значение, введенные​ маску ввода этого​ необходимо создать настраиваемую​ контекстном меню команду​В разделе​

​. , : ; — /​​ другой знак, введите​Примеры масок ввода​Case 3, 6​Case «1», «2»​ уже изменяется​ 6 цифр​Iгор прокопенко​ ругался, а сам​ пункт ‘Форма…’.Comanche,​​ ячейки на листе​ автоматически распознает это​ данные будут отклонены​ типа, необходимо задать​ маску ввода.​Свойства​Свойства поля​Разделитель целой и дробной​ его в третьем​Использование масок ввода для​iPos = iPos​iL = Asc(«0»)​т. е. будет​​If t Like​​: Нужно поставить формат​​ переделывал, например человек​​именно: ‘1. Форма​ через меню Данные->Проверка…​ значение как дату.​ и появится сообщение,​ для типа данных​В области «Свойства поля»​.​на вкладке​ части, групп разрядов,​ компоненте маски.​ адресов электронной почты​ — 2​iR = Asc(«9»)​ ;#-;-; # и​​ «;-;-;» Then t​ ячеек «общий».​ вводит : «петров​ как ‘UserForm’ -​

CyberForum.ru>

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

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)

Inputmask.extendDefinitions({
  '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"
  }
});

set defaults

Defaults can be set as below.

Inputmask.extendDefaults({
  'autoUnmask': true
});
Inputmask.extendDefinitions({
  'A': {
    validator: "",
    cardinality: 1,
    casing: "upper" //auto uppercasing
  },
  '+': {
    validator: "",
    cardinality: 1,
    casing: "upper"
  }
});
Inputmask.extendAliases({
  'Regex': {
    mask: "r",
    greedy: false,
    ...
  }
});

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

Inputmask.extendAliases({
  'numeric': {
    allowPlus: false,
    allowMinus: false
  }
});

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: '',
    allowPlus: false,
    allowMinus: false
  }
});

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({
  onKeyValidation: function(key, result){
    if (!result){
      alert('Your input is not valid')
    }
  }
});

Alias definitions

date & datetime aliases

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

The date aliases take leapyears 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(){
   $("#date").inputmask("datetime"); // 24h
   $("#date").inputmask("datetime12"); // am/pm
});

numeric aliases

$(document).ready(function(){
   $("#numeric").inputmask("decimal");
   $("#numeric").inputmask("non-negative-decimal");
   $("#numeric").inputmask("integer");
});

With the decimal mask the caret will always jump to the integer part, until you type the radixpoint.
There is autocompletion on tab with decimal numbers.

Define the radixpoint

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

Define the number of digits after the radixpoint

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

Grouping support through: autoGroup, groupSeparator, groupSize

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

other aliases

An ip adress alias for entering valid ip-addresses.

$(document).ready(function(){
   $(selector).inputmask("ip");
});

You can find/modify/extend this alias in the jquery.inputmask.extensions.js

Определение пользовательского символа маски

Вы можете определить свои собственные символы для использования в вашей маске. Начните с выбора символа маски.

валидатор(chrs, maskset, pos, strict, opts)

Затем определите свой валидатор. Проверка может быть регулярным выражением или функцией.

Возвращаемое значение валидатор может быть истинным, ложным или объектом.

Опциональные команды

  • pos : позиция для вставки

  • c : символ для вставки

  • caret : позиция каретки

  • remove : позиция (позиции) для удаления

    pos или

  • insert : позиции (позиций) для добавления :

    • { pos : позиция вставки, c : символ для вставки }
  • refreshFromBuffer :

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

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

Опция предварительной проверки используется для проверки символов перед кардинальным определением, которое будет достигнуто. (См ‘J’ пример)

definitionSymbol

При вставке или удалении символов, они смещаются только тогда, когда определение типа является то же самое. Такое поведение может быть отменено, давая definitionSymbol. (См пример х, у, z, который может быть использован для IP-адреса маски, проверка отличается, но допускается сдвиг символов между определениями)

Inputmask.extendDefinitions({
  '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" //это позволяет сдвига значениt из других определений, с тем же символом маски или определения символа
  },
  '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"
  }
});

set defaults

Значения по умолчанию могут быть установлены, как показано ниже.

Inputmask.extendDefaults({
  'autoUnmask': true
});
Inputmask.extendDefinitions({
  'A': {
    validator: "",
    cardinality: 1,
    casing: "upper" //автоматический перевод в верхний регистр
  },
  '+': {
    validator: "",
    cardinality: 1,
    casing: "upper"
  }
});
Inputmask.extendAliases({
  'Regex': {
    mask: "r",
    greedy: false,
    ...
  }
});

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

Inputmask.extendAliases({
  'numeric': {
    allowPlus: false,
    allowMinus: false
  }
});

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

Inputmask.extendAliases({
  'myNum': {
    alias: "numeric",
    placeholder: '',
    allowPlus: false,
    allowMinus: false
  }
});

После того, как определено, вы можете вызвать псевдоним с помощью:

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

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

Inputmask.extendDefaults({
  onKeyValidation: function(key, result){
    if (!result){
      alert('Ваше введенное значение не верно')
    }
  }
});

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.

Methods:

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 =newInputmask("99-999-99");im.mask(document.querySelectorAll(selector));

or

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

Get the

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

or

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

Unmask a given value against the mask.

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

Remove the .

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

or

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

or

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

return the default (empty) mask value

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

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(){functionvalidateMaskedValue(val){}functionvalidateValue(val){}var val =$("#test").val();if($("#test").inputmask("hasMaskedValue"))validateMaskedValue(val);elsevalidateValue(val);});

Verify whether the current value is complete or not.

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

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

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.

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({onBeforePastefunction(pastedValue,opts){returnphoneNumOnPaste(pastedValue, opts);}});
$("#CellPhone").inputmask("option",{onBeforePastefunction(pastedValue,opts){returnphoneNumOnPaste(pastedValue, opts);}})

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

Validate a given value against the mask.

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

3 ответов

Supported markup options

<inputid="test"dir="rtl" />
<inputid="test"readonly="readonly" />
<inputid="test"disabled="disabled" />
<inputid="test"maxlength="4" />

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 {}.

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

All options can also be passed through data-attributes.

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

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

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

Воспользоваться Intercepter-NG

Неплохой способ вспомнить пароль – прибегнуть к помощи особой утилиты Intercepter-NG. Несмотря на то, что она скорее предназначена для хакеров, можно её преимущества использовать для решения этой проблемы.

После входа в любой аккаунт или программу, как только произойдёт автоматическая авторизация, Intercepter-NG сделает своё дело – обнаружит сведения для входа и зафиксирует информацию в отдельном текстовом файле. Останется открыть этот отчёт и увидеть логин с паролем для входа на конкретный сайт или в приложение. Надо добавить, что корректная работа этой программы возможна только на смартфонах с включёнными рут правами.

Способ второй: переводим проценты в десятичную дробь

Как вы помните, процент — сотая часть числа. В виде десятичной дроби это 0,01 (ноль целых одна сотовая). Следовательно, 17% – это 0,17 (ноль целых, семнадцать сотых), 45% – 0,45 (ноль целых, сорок пять сотых) и т. д. Полученную десятичную дробь умножаем на сумму, процент от которой считаем. И находим искомый ответ.

Например, давайте рассчитаем сумму подоходного налога от зарплаты 35 000 рублей. Налог составляет 13%. В виде десятичной дроби это будет 0,13 (ноль целых, тринадцать сотых). Умножим сумму 35 000 на 0,13. Получится 4 550. Значит, после вычета подоходного налога вам будет перечислена зарплата 35 000 – 4 550 = 30 050. Иногда эту сумму уже без налога называют «зарплатой на руки» или «чистой». В противовес этому сумму вместе с налогом «грязной зарплатой». Именно «грязную зарплату» указывают в объявлениях о вакансиях компании и в трудовом договоре. На руки же даётся меньше. Сколько? Теперь вы легко посчитаете.

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

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)

Usage

First, include the jQuery and masked input javascript files.

<script src="jquery.js" type="text/javascript"></script>
<script src="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.

Method Details

hashPluginOptions()

protected method

Generates a hashed variable to store the plugin .

Helps in reusing the variable for similar
options passed for other widgets on the same page. The following special data attribute will also be
added to the input field to allow accessing the client options via javascript:

‘data-plugin-inputmask’ will store the hashed variable storing the plugin options.

protected void ( $view )
$view yii\web\View

The view instance

init()

public method

Initializes the widget.

public void ( )
throws yii\base\InvalidConfigException

if the «mask» property is not set.

initClientOptions()

protected method

Initializes client options.

protected void ( )

registerClientScript()

public method

Registers the needed client script and options.

public void ( )

run()

public method

Executes the widget.

public string ( )
return string

The result of widget execution to be outputted.

Добавить комментарий

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

Adblock
detector