Class yii\widgets\maskedinput

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

Применение:

Подключите 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-файлах или путем дальнейшего изучения опций.

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.

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

3 ответов

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

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

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

Маска ввода полю в форме в 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>

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

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

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.

Property Details

$_hashVar
protected property

The hashed variable to store the pluginOptions

protected string = null

$aliases
public property

Custom aliases to use. Should be configured as , where

  • is a string containing a text to identify your mask alias definition (e.g. ‘phone’) and
  • is an array containing settings for the mask symbol, exactly similar to parameters as passed in .

public array = null

$clientOptions
public property

The JQuery plugin options for the input mask plugin.

See also https://github.com/RobinHerbots/Inputmask.

public array = []

$definitions
public property

Custom mask definitions to use. Should be configured as , where

  • is a string, containing a character to identify your mask definition and
  • is an array, consisting of the following entries:

    • : string, a JS regular expression or a JS function.
    • : int, specifies how many characters are represented and validated for the definition.
    • : array, validate the characters before the definition cardinality is reached.
    • : string, allows shifting values from other definitions, with this .

public array = null

$mask
public property

The input mask (e.g. ’99/99/9999′ for date input). The following characters
can be used in the mask and are predefined:

  • : represents an alpha character (A-Z, a-z)
  • : represents a numeric character (0-9)
  • : represents an alphanumeric character (A-Z, a-z, 0-9)
  • and : anything entered between the square brackets is considered optional user input. This is
    based on the setting in .

Additional definitions can be set through the property.

public string|array|yii\web\JsExpression = null

$options
public property

The HTML attributes for the input tag.

See also for details on how attributes are being rendered.

public array = [‘class’ => ‘form-control’

$type
public property
(available since version 2.0.6)

The type of the input tag. Currently only ‘text’ and ‘tel’ are supported.

See also https://github.com/RobinHerbots/Inputmask.

public string = ‘text’

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

InputMask public properties, getters & setters

The value the mask will have when none of its editable data has been filled in.

The current selection within the input represented as an object with and properties, where .

If and are the same, this indicates the current cursor position in the string, otherwise it indicates a range of selected characters within the string.

will be updated as necessary by editing methods, e.g. if you a valid character, will be updated to place the cursor after the newly-inserted character.

If you’re using as the backend for an input mask in a GUI, make sure is accurate before calling any editing methods!

Sets the selection and performs an editable cursor range check if the selection change sets the cursor position (i.e. and are the same).

If the mask’s pattern begins or ends with static characters, this method will prevent the cursor being placed prior to a leading static character or beyond a tailing static character. Only use this method to set if this is the behaviour you want.

Returns if the selection needed to be adjusted as described above, otherwise.

Gets the current value in the mask, which will always conform to the mask’s pattern.

Gets the current value in the mask without non-editable pattern characters.

This can be useful when changing the mask’s pattern, to «replay» the user’s input so far into the new pattern:

var mask = new InputMask({pattern: '1111 1111', value: '98781'})
mask.getValue()
// → '9878 1___'
mask.getRawValue()
// → '98781'

mask.setPattern('111 111', {value: mask.getRawValue()})
mask.getValue()
// → '987 81_'

Overwrites the current value in the mask.

The given value will be applied to the mask’s pattern, with invalid — or missing — editable characters replaced with placeholders.

The value may optionally contain static parts of the mask’s pattern.

Sets the mask’s pattern. The mask’s value and selection will also be reset by default.

Можно ли восстановить удалённые сообщения на iPhone

Не во всех случаях имеется возможность восстановить SMS-сообщения. Для восстановления нужно чтобы:

  1. СМС-сообщения были удалены или утеряны недавно.
  2. После утери iPhone не был перезагружен, и оперативная память не была переполнена, иначе кеш-память, в которой и находятся стёртые СМС, уничтожается.
  3. Текстовые сообщения находились на Сим-карте, а не в памяти iPhone.

Только если все упомянутые выше условия соблюдены, можно начинать восстанавливать удалённые СМС, но прежде нужно проверить раздел «Сообщения», ведь иногда в этом разделе есть пункт «Удалённые», а там могут храниться все удалённые пользователем текстовые сообщения и чаты.

В случае если проверка папки «Удалённые» и использование методов восстановления с помощью iTunes и iCloud не помогли, можно попробовать воспользоваться специальными программами, которые предназначены для восстановления СМС.

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 : alfabetic

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

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 upper/lower- casing inputmask

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

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
});
Добавить комментарий

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

Adblock
detector