Маска ввода для html элемента input

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

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.

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

Masking types

Static masks

These are the very basics 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 is optional. This is done by using .

Example:

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

This mask will allow input like or .

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

skipOptionalPartCharacter

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

skipOptionalPartCharacter: " "

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

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

For example, given:

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

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

Optional masks with greedy false

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

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

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

Dynamic masks

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

{n} => n repeats
{n|j} => n repeats, with j jitmasking
{n,m} => from n to m repeats
{n,m|j} => from n to m repeats, with j jitmasking

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!#$%&'*+/=?^_`{|}~\-]",
        casing: "lower"
      }
    }
  });
  //decimal mask
   Inputmask("(.999){+|1},00", {
        positionCaretOnClick: "radixFocus",
        radixPoint: ",",
        _radixDance: true,
        numericInput: true,
        placeholder: "0",
        definitions: {
            "0": {
                validator: ""
            }
        }
   }).mask(selector);
});

Alternator masks

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

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

Also make sure to read about the option.

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

or

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

Preprocessing masks

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

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

JIT Masking

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

Value can be true or a threshold number or false.

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

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

Usage:

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

via Inputmask class

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

via jquery plugin

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

or with the bundled version

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

via data-inputmask attribute

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

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

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

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

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

If you use a module loader like requireJS

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

Example config.js

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

As dependencyLib you can choose between the supported libraries.

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

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

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.

Применение:

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

Customization

Initalization

If you are ok with all the default options you can have masked-inputs initalize it self and avoid writing any JavaScript at all. Simply add the attribute to your script tag

Alternativly if you need to pass custom options or want to initalize the script your self you can do so like this

new InputMask( *options* );

masked

Don’t like the class for a selector? Pass an options object instead and set your selector with the masked property or event pass a .

// Selector
new InputMask({
  masked: ".custom-selector"
});

// Node List
new InputMask({
  masked: nodeList
});

number

Want to use something other than X? right now the script handles XdDmMyY9 for numeric placeholding. MM/YY and mm/yy will work fine. Want to use something else, simply pass an options object setting the option.

// Selector
new InputMask({
  number: 'XZdDmMyY9'
});

letter

Want to use something other than X in your placeholder look for masked inputs that require both letters and numbers, you can. You can put different characters in your placeholder, as long as your contains Xs and _ only.

<input placeholder="XXX XXX" pattern="\w\d\w \d\w\d" class="masked" 
      data-charset="?X? X?X" id="zipca" type="text" name="canadianzip" 
        title="6-character alphanumeric code in the format of A1A 1A1">

If you require _ as a special character in your mask? Simply pass an options object setting the option, and also the value of in your HTML.

new InputMask({
  letter: '?'
});
<input placeholder="XXX_XXX" pattern="\w\d\w\_\d\w\d" class="masked" 
      data-charset="?X?_X?X" id="underscore" type="text" name="underscoredstring" 
        title="6-character alphanumeric code in the format of A1A_1A1">

onError

Want to add error handling? Simply pass a function to the option. The function will recieve the keyboard event as the first paramater.

new InputMask({
  onError: function( e ) {
    // Handle your errors!
  }
});

noValidate

As the pattern attribute is being used, you may want to add via javascript the novalidate attribute on any ancestor or form control to disable native browser validation. Do add it via JS, because if the JS fails, native validation is a good alternative.

You can have input masking do this for you by setting the option to true.

new InputMask({
  noValidate: true
});

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

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 the 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": "99/99/9999", '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)
});

escape special mask chars

If you want a mask element to appear as a static element you can escape them by \

$(document).ready(function(){
  $("#months").inputmask("m \\months");
});

Extra example see https://github.com/RobinHerbots/Inputmask/issues/2251

auto-casing inputmask

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Методы:

mask(elems)

Создание маски ввода

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

или

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

или

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

или

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

или

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

unmaskedvalue

Get the

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

или

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

удаление

Удаление .

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

или

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

или

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

Проверьте маскируется ли возвращаемое значение или нет; В настоящее время только надежно работает при использовании jquery.val функции для извлечения значения

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

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

isComplete

Проверяет, осуществлен ли полный ввод значения или нет

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

getmetadata

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

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

установка значения

SetValue функциональность, чтобы установить значение для inputmask, как вы могли бы сделать с jQuery.val, но это вызовет внутреннее событие, используемый inputmask всегда, в любом случае. Это особенно полезно при клонировании inputmask с jQuery.clone. Клонирование inputmask не является полностью функциональным клоном. На первом случае (MouseEnter, фокус …) сотрудник inputmask может обнаружить, если он где клонировали может активировать маскирование. Однако при установке значения с jQuery.val не существует ни одно из событий сработавших в этом случае. SetValue функциональность делает это для вас.

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

Формат

Вместо того, чтобы маскировать входного элемента также можно использовать для форматирования inputmask для форматирования заданных значений. Подумайте о форматировании значений, чтобы показать в jqGrid или на других элементах затем вводит.

var formattedDate = Inputmask.format("2331973", { alias: "dd/mm/yyyy"});
var isValid = Inputmask.isValid("23/03/1973", { alias: "dd/mm/yyyy"});
Добавить комментарий

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

Adblock
detector