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

3 ответов

InputMask history methods

An creates a new history snapshot each time you:

  • Perform a different type of editing operation to the previous editing operation.
  • Perform an editing operation with the cursor in a different position from where it was left after a previous editing operation.
  • Perform an editing operation with a text selection.

History methods allow you to step backwards and forwards through these snapshots, updating and accordingly.

If you perform an editing operation while stepping backwards through history snapshots, all snapshots after the current one will be disposed of.

A history method returns if a valid history operation was performed and and have been updated.

Otherwise, if an invalid history operation is attempted (e.g. trying to redo when you’ve already reached the point undoing started from) it will return .

Steps backwards through history snapshots.

Steps forwards through history snapshots.

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

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

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

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.

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

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.

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

numeric extensions

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

RadixDance

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. You can disable this behaviour by setting the skipRadixDance to true.

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

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(){
   $("#numeric").inputmask("decimal", { radixPoint: ",", autoGroup: true, groupSeparator: ".", groupSize: 3 });
});

Allow minus and/or plus symbol

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

Применение:

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

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

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 inputmask.js && jquery.inputmask.js

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

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

{@inheritdoc}

public void ( )

Примеры масок ввода

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

Обеспечивает ввод значения в виде

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

(206) 555-0199( ) 555-0199

В этом случае в области междугородного кода используется местозаполнитель 9, поэтому междугородные коды необязательны. Кроме того, восклицательный знак (!) обусловливает заполнение маски слева направо.

Предоставляется возможность заменить буквами четыре последних цифры телефонного номера в формате США

Обратите внимание на местозаполнитель 0 в области кода города, который делает междугородный код обязательным

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

ЗЕЛЕНЫЙ339М3 МАЙ Р 452Б7

Сочетание обязательных (L) и необязательных (?) букв и обязательных цифр (0). Знак «больше» требует вводить все буквы в верхнем регистре. Чтобы использовать маску ввода этого типа, необходимо задать для типа данных поля таблицы значение Текстовый или Поле МЕМО.

Обязательный почтовый индекс и необязательная область четырехзначного расширения.

Сочетание обязательных букв и цифр, все в верхнем регистре. Данный тип маски ввода помогает, например, правильно вводить инвентарные номера или заполнять другие формы складского учета.

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

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

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

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

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

Как вы помните, процент — сотая часть числа. В виде десятичной дроби это 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. Иногда эту сумму уже без налога называют «зарплатой на руки» или «чистой». В противовес этому сумму вместе с налогом «грязной зарплатой». Именно «грязную зарплату» указывают в объявлениях о вакансиях компании и в трудовом договоре. На руки же даётся меньше. Сколько? Теперь вы легко посчитаете.

Usage

Simply include

<script src="cleave.min.js"></script>
<script src="cleave-phone.{country}.js"></script>

Then have a text field

<input class="input-phone" type="text"/>

Now in your JavaScript

var cleave = new Cleave('.input-phone', {
    phone: true,
    phoneRegionCode: '{country}'
});

CommonJS

var Cleave = require('cleave.js');
require('cleave.js/dist/addons/cleave-phone.{country}');

var cleave = new Cleave(...)

AMD

require('cleave.js/dist/cleave.min', 'cleave.js/dist/addons/cleave-phone.{country}', function (Cleave) {
    var cleave = new Cleave(...)
});

ES Module

// Rollup, WebPack
import Cleave from 'cleave.js';
var cleave = new Cleave(...)

// Browser
import Cleave from 'node_modules/cleave.js/dist/cleave-esm.min.js';
var cleave = new Cleave(...)

TypeScript

Types are contributed by the community and are available via . Once installed, you can import Cleave like the following:

import Cleave = require('cleave.js');

Types for the React-component are also available and can be imported in the same way.

import Cleave = require('cleave.js/react');
Добавить комментарий

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

Adblock
detector