Маска ввода в полях формы на jquery

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

mask

is an array or a function that defines how the user input is going to be masked.

array

The way to define a mask in Text Mask is through an array.

Each element in the array has to be either a string or a regular expression. Each string is a fixed character in the mask
and each regular expression is a placeholder that accepts user input.

The regular expression will be used to test user input and either allow it or reject it.

For example, a mask for a U.S. phone number such as , could be:

'(', /1-9/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/

That means the user can enter only a number between 1 and 9 in the first placeholder, and only a digit in the placeholders
after that.

Any valid regular expressions should work.

Note: it is possible to set the mask to to disable masking completely.

function

You can also pass a function as the . The function will receive the user input at every
change. The function is expected to return a array as described above.

var mask = function(rawValue) {
  // add logic to generate your mask array
  return  /*your mask array*/ 
}

For an example of a mask function, see the source code of
,
which is a .

Note: it is possible to return from a mask function to disable masking completely.

⚙️ Configuration

Library provides several ways to apply the mask.

The first and the easiest one is to use default placeholders.

Default placeholders

This approach is good for simple cases. No configuration is required.

import Vue from 'vue'
import VueMask from 'v-mask'
Vue.use(VueMask)
<template>
  <input type="text" v-mask="'####-##'" v-model="myInputModel">
</template>
<script>
  export default {
    data () => ({
      myInputModel ''
    })
  }
</script>

Entering in the input field will produce value in variable.

Here is a list placeholders you can utilize by default:

Placeholder Format
# Number (0-9)
A Letter in any case (a-z,A-Z)
N Number or letter (a-z,A-Z,0-9)
X Any symbol
? Optional (next character)

Custom placeholders

While default placeholders are easy to use and straightforward in reality we have to deal with more complex cases where validation can be a bit more complex and unpredictable. In such cases it makes sense to define custom placeholders specific to the project or the domain.

To define them you should pass them as an object while installing plugin. Where:

  • is the character in a mask
  • is regular expression used to verify entered symbol

You can disable any default placeholder by passing placeholder as a key and as a value.

Any valid string character can be used as a placeholder (e.g. Cyrillic or Arabic)

import Vue from 'vue'
import VueMask from 'v-mask'

Vue.use(VueMask, {
  placeholders: {
    '#': null,       // passing `null` removes default placeholder, so `#` is treated as character
    D: /\d/,         // define new placeholder
    Я: /\wа-яА-Я/, // cyrillic letter as a placeholder
  }
})
<template>
  <input type="text" v-mask="'###-DDD-###-DDD'" v-model="myInputModel">
</template>
<script>
  export default {
    data () => ({
      myInputModel ''
    })
  }
</script>

Entering in that input field will produce value in variable.

Array of RegExp

In some cases you might not want to define global placeholders either because you are dealing with unique input or you are facing conflicts for placeholders in several places.

In such cases you can supply array of per-char regular excursions or static characters to .

import Vue from 'vue'
import VueMask from 'v-mask'
Vue.use(VueMask)
<template>
  <input type="text" v-mask="mask" v-model="myInputModel">
</template>
<script>
  export default {
    data () => ({
      mask ,
      myInputModel ''
    })
  }
</script>

In this example entering in the input field will produce value in variable.

Notice: Keep in mind that library always verifies one character per regular expression. Trying verify multiple charters in the same RegExp won’t work.

Function

If custom placeholder and array of RegExps can’t fit your needs there is one more way you can use to mask a value.
The idea beneath is that you can write a function that is used by library to format the output.

This approach is super powerful but also more complex to write and understand so try previous ones first.

The function will be given a value from the input. It should return array of per-char regular expressions & static characters:

import Vue from 'vue'
import VueMask from 'v-mask'
Vue.use(VueMask)
<template>
  <input type="text" v-mask="mask" v-model="myInputModel" placeholder="00:00-23:59">
</template>
<script>
  /**
   * Generate a time mask based on input value (23:59)
   * @param {string} value
   */
  export function timeMask(value) {
    const hours = ,
      value.charAt() === '2' ?   ,
    ];
    const minutes = , ];
    return value.length > 2
      ? 
       hours;
  }

  /**
   * Generate a time range mask based on input value (00:00-23:59)
   * @param {string} value
   */
  export function timeRangeMask(value) {
    const numbers = value.replace(g, '');
    if (numbers.length > 4) {
      return ;
    }
    return ;
  }

  export default {
    data () => ({
      mask timeRangeMask,
      myInputModel ''
    })
  }
</script>

In this example entering in the input field will produce valid time range in variable.

Text Mask Addons

The usage is simple. Configure the addon as want and pass the result to the as you would to .

import Vue from 'vue'
import VueMask from 'v-mask'
Vue.use(VueMask)
<template>
  <input type="text" v-mask="mask" v-model="myInputModel" placeholder="$100.00">
</template>
<script>
  import createNumberMask from 'text-mask-addons/dist/createNumberMask';
  const currencyMask = createNumberMask({
    prefix '$',
    allowDecimal true,
    includeThousandsSeparator true,
    allowNegative false,
  });
  export default {
    data () => ({
      mask currencyMask,
      myInputModel ''
    })
  }
</script>

In this example:

  • entering in the input field will produce in variable
  • while entering in the input field will produce

View the documentation for a full list of options available.

Experimental 🔥

The following props are considered experimental because they are more prone to issues and are likely to be changed in the future. Use with caution.

In case you need to implement more complex masking behavior, you can provide function to change masked value and cursor position before it will be applied to the input. receives following arguments:

  1. newState (object): New input state. Contains and fields. is null on input blur or when function is called before input mount. Example:
  2. oldState (object): Input state before change. Contains and fields. is null on input focus or when function is called before input mount.
  3. userInput (string): Raw entered or pasted string. if user didn’t enter anything (e.g. triggered by deletion or rerender due to props change).
  4. maskOptions (object): Mask options. Example:
{  mask'99/99/9999',  maskChar'_',  alwaysShowMaskfalse,  formatChars{'9''','a''','*'''},  permanents2,5}

must return an object with following fields:

  1. value (string): New value.
  2. selection (object): New selection. If in argument is null, it must be null too.

Please note that executes more often than and must be pure.

To use another component instead of regular pass render function as a children. Function receives argument which contains props that aren’t used by react-input-mask’s internals. I.e. it passes down every prop except the following ones: , , , , , , , . These properties, if used, should always be passed directly to react-input-mask instead of children and shouldn’t be altered in chldren’s function.

import React from'react';import InputMask from'react-input-mask';import MaterialInput from'@material-ui/core/Input';constInput=(props)=>(<InputMaskmask="99/99/9999"value={props.value}onChange={props.onChange}>{(inputProps)=><MaterialInput{...inputProps}type="tel"disableUnderline/>}</InputMask>);constInvalidInput=(props)=>(<InputMaskmask="99/99/9999"value={props.value}>{(inputProps)=><MaterialInput{...inputProps}type="tel"disableUnderlineonChange={props.onChange}/>}</InputMask>);
import React from'react';import InputMask from'react-input-mask';classPhoneInputextendsReact.Component{render(){return<InputMask{...this.props}mask="+4\9 99 999 99"maskChar=""/>;}}

Mask for ZIP Code. Uses beforeMaskedValueChange to omit trailing minus if it wasn’t entered by user:

import React from'react';import InputMask from'react-input-mask';classInputextendsReact.Component{  state ={    value''}onChange=(event)=>{this.setState({      valueevent.target.value});}beforeMaskedValueChange=(newState,oldState,userInput)=>{var{ value }= newState;var selection =newState.selection;var cursorPosition = selection ?selection.startnull;if(value.endsWith('-')&& userInput !=='-'&&!this.state.value.endsWith('-')){if(cursorPosition ===value.length){        cursorPosition--;        selection ={ start cursorPosition, end cursorPosition };}      value =value.slice(,-1);}return{      value,      selection};}render(){return<InputMaskmask="99999-9999"maskChar={null}value={this.state.value}onChange={this.onChange}beforeMaskedValueChange={this.beforeMaskedValueChange}/>;}}

Browser’s autofill requires either empty value in input or value which exactly matches beginning of the autofilled value. I.e. autofilled value «+1 (555) 123-4567» will work with «+1» or «+1 (5», but won’t work with «+1 (___) ___-____» or «1 (555)». There are several possible solutions:

  1. Set to null and trim space after «+1» with if no more digits are entered.
  2. Apply mask only if value is not empty. In general, this is the most reliable solution because we can’t be sure about formatting in autofilled value.
  3. Use less formatting in the mask.

Please note that it might lead to worse user experience (should I enter +1 if input is empty?). You should choose what’s more important to your users — smooth typing experience or autofill. Phone and ZIP code inputs are very likely to be autofilled and it’s a good idea to care about it, while security confirmation code in two-factor authorization shouldn’t care about autofill at all.

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.

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

date & datetime extensions

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

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

Initialization

ES2015 (Webpack/Rollup/Browserify/etc)

import Vue from 'vue'

// As a plugin
import VueMask from 'v-mask'
Vue.use(VueMask);

// Or as a directive
import { VueMaskDirective } from 'v-mask'
Vue.directive('mask', VueMaskDirective);

// Or only as a filter
import { VueMaskFilter } from 'v-mask'
Vue.filter('VMask', VueMaskFilter)

UMD (Browser)

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/v-mask/dist/v-mask.min.js"></script>
<script>
// As a plugin
Vue.use(VueMask.VueMaskPlugin);

// Or as a directive
Vue.directive('mask', VueMask.VueMaskDirective);
</script>

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

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.

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

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

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

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

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

Оцените статью
Рейтинг автора
5
Материал подготовил
Илья Коршунов
Наш эксперт
Написано статей
134
Добавить комментарий