PHPackages                             sgu-infocom-official/inputmask\_v3.3.11 - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. sgu-infocom-official/inputmask\_v3.3.11

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

sgu-infocom-official/inputmask\_v3.3.11
=======================================

Inputmask is a javascript library which creates an input mask. Inputmask can run against vanilla javascript, jQuery and jqlite.

5.0.9(2y ago)0480↓64.3%MIT

Since Jan 28Pushed 1y agoCompare

[ Source](https://github.com/SGU-infocom-official/Inputmask_v3.3.11)[ Packagist](https://packagist.org/packages/sgu-infocom-official/inputmask_v3.3.11)[ Docs](http://robinherbots.github.io/Inputmask)[ RSS](/packages/sgu-infocom-official-inputmask-v3311/feed)WikiDiscussions master\_3.3.11 Synced today

READMEChangelogDependenciesVersions (203)Used By (0)

Inputmask 3.x
=============

[](#inputmask-3x)

Copyright (c) 2010 - 2017 Robin Herbots Licensed under the MIT license ()

[![NPM Version](https://camo.githubusercontent.com/8de1c598a196018b7b5c45b90ad12540ae8179d686402e7729fee372c5fbccb9/68747470733a2f2f696d672e736869656c64732e696f2f6e706d2f762f696e7075746d61736b2e737667)](https://npmjs.org/package/inputmask) [![Dependency Status](https://camo.githubusercontent.com/3ab37f39e8b2cc45896a1b3624ba07e83affeb337296d69df596eb9ee4f12c2b/68747470733a2f2f696d672e736869656c64732e696f2f64617669642f526f62696e486572626f74732f696e7075746d61736b2e737667)](https://david-dm.org/RobinHerbots/inputmask#info=dependencies) [![devDependency Status](https://camo.githubusercontent.com/77f928582b75fa8f3fb188606b02a428472786bbf99f4bf0012c1157de889908/68747470733a2f2f696d672e736869656c64732e696f2f64617669642f6465762f526f62696e486572626f74732f696e7075746d61736b2e737667)](https://david-dm.org/RobinHerbots/inputmask#info=devDependencies)

Inputmask is a javascript library which creates an input mask. Inputmask can run against vanilla javascript, jQuery and jqlite.

An inputmask helps the user with the input by ensuring a predefined format. This can be useful for dates, numerics, phone numbers, ...

Highlights:

- easy to use
- optional parts anywere in the mask
- possibility to define aliases which hide complexity
- date / datetime masks
- numeric masks
- lots of callbacks
- non-greedy masks
- many features can be enabled/disabled/configured by options
- supports readonly/disabled/dir="rtl" attributes
- support data-inputmask attribute(s)
- alternator-mask
- regex-mask
- dynamic-mask
- preprocessing-mask
- JIT-masking
- value formatting / validating without input element
- AMD/CommonJS support
- dependencyLibs: vanilla javascript, jQuery, jqlite
- [Android support](README_android.md)

Demo page see

[![donate](https://camo.githubusercontent.com/7b6de155df30b37b25eb5fec52f9213680c3dbf067dfb7d7e2850ac4096c7d05/68747470733a2f2f7777772e70617970616c6f626a656374732e636f6d2f656e5f55532f692f62746e2f62746e5f646f6e6174655f534d2e676966)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=ZNR3EB6JTMMSS)

Setup
-----

[](#setup)

### dependencyLibs

[](#dependencylibs)

Inputmask can run against different javascript libraries.
You can choose between:

- inputmask.dependencyLib (vanilla)
- inputmask.dependencyLib.jquery
- inputmask.dependencyLib.jqlite
- .... (others are welcome)

### Classic web with &lt;script&gt; tag

[](#classic-web-with-script-tag)

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

If you want to include the Inputmask and all extensions. (with jQuery as dependencylib)

```

```

For individual extensions. (with jQuery as dependencylib)

```

```

For individual extensions. (with vanilla dependencylib)

```

```

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

```

```

### webpack

[](#webpack)

#### Install the package

[](#install-the-package)

```
npm install inputmask --save-dev

```

#### In your modules

[](#in-your-modules)

If you want to include the Inputmask and all extensions.

```
var Inputmask = require('inputmask');

//es6
import Inputmask from "inputmask";

```

For individual extensions.
Every extension exports the Inputmask, so you only need to import the extensions.
See example.

```
require("inputmask/dist/inputmask/inputmask.numeric.extensions");
var Inputmask = require("inputmask/dist/inputmask/inputmask.date.extensions");

//es6
import "inputmask/dist/inputmask/inputmask.numeric.extensions";
import Inputmask from "inputmask/dist/inputmask/inputmask.date.extensions";

```

#### Selecting the dependencyLib

[](#selecting-the-dependencylib)

By default the vanilla dependencyLib is used. You can select another dependency by creating an alias in the webpack.config.

```
 resolve: {
        alias: {
            "./dependencyLibs/inputmask.dependencyLib": "./dependencyLibs/inputmask.dependencyLib.jquery"
        }
    },

```

Usage
-----

[](#usage)

### via Inputmask class

[](#via-inputmask-class)

```
var selector = document.getElementById("selector");

var im = new Inputmask("99-9999999");
im.mask(selector);

//or

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

[](#via-jquery-plugin)

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

[](#via-data-inputmask-attribute)

```

```

```
$(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-&lt;***the name of the option***&gt;="value"

[](#any-option-can-also-be-passed-through-the-use-of-a-data-attribute-use-data-inputmask-the-name-of-the-optionvalue)

```

```

```
$(document).ready(function(){
  $("#example1").inputmask("99-9999999");
  $("#example2").inputmask();
});
```

### Allowed HTML-elements

[](#allowed-html-elements)

- ``
- ``
- ``
- `` (and all others supported by contenteditable)
- ``
- any html-element (mask text content or set maskedvalue with jQuery.val)

The allowed input types are defined in the supportsInputType option. Also see ([input-type-ref](https://html.spec.whatwg.org/multipage/forms.html#do-not-apply))

### Default masking definitions

[](#default-masking-definitions)

- `9` : numeric
- `a` : alphabetical
- `*` : alphanumeric

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

Masking types
-------------

[](#masking-types)

### Static masks

[](#static-masks)

These are the very basic of masking. The mask is defined and will not change during the input.

```
$(document).ready(function(){
  $(selector).inputmask("aa-9999");  //static mask
  $(selector).inputmask({mask: "aa-9999"});  //static mask
});
```

### Optional masks

[](#optional-masks)

It is possible to define some parts in the mask as optional. This is done by using \[ \].

Example:

```
$('#test').inputmask('(99) 9999[9]-9999');
```

This mask wil allow input like `(99) 99999-9999` or `(99) 9999-9999`.

Input =&gt; 12123451234 mask =&gt; (12) 12345-1234 (trigger complete)
Input =&gt; 121234-1234 mask =&gt; (12) 1234-1234 (trigger complete)
Input =&gt; 1212341234 mask =&gt; (12) 12341-234\_ (trigger incomplete)

#### skipOptionalPartCharacter

[](#skipoptionalpartcharacter)

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

```
skipOptionalPartCharacter: " "
```

Input =&gt; 121234 1234 mask =&gt; (12) 1234-1234 (trigger complete)

When `clearMaskOnLostFocus: true` 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[-AAA]');
```

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 `123`. When both the required and optional parts of the mask are filled out and the field loses focus, the user will see `123-ABC`.

#### Optional masks with greedy false

[](#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[-9999]", greedy: false });
```

The initial mask shown will be "**\_**" instead of "**\_**-\_\_\_\_".

### Dynamic masks

[](#dynamic-masks)

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

{n} =&gt; n repeats
{n,m} =&gt; from n to m repeats

Also {+} and {\*} is allowed. + start from 1 and \* start from 0.

```
$(document).ready(function(){
  $(selector).inputmask("aa-9{4}");  //static mask with dynamic syntax
  $(selector).inputmask("aa-9{1,4}");  //dynamic mask ~ the 9 def can be occur 1 to 4 times

  //email mask
  $(selector).inputmask({
    mask: "*{1,20}[.*{1,20}][.*{1,20}][.*{1,20}]@*{1,20}[.*{2,6}][.*{1,2}]",
    greedy: false,
    onBeforePaste: function (pastedValue, opts) {
      pastedValue = pastedValue.toLowerCase();
      return pastedValue.replace("mailto:", "");
    },
    definitions: {
      '*': {
        validator: "[0-9A-Za-z!#$%&'*+/=?^_`{|}~\-]",
        cardinality: 1,
        casing: "lower"
      }
    }
  });
});
```

### Alternator masks

[](#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" =&gt; a or 9
"(aaa)|(999)" =&gt; aaa or 999
"(aaa|999|9AA)" =&gt; aaa or 999 or 9AA

Also make sure to read about the keepStatic option.

```
$("selector").inputmask("(99.9)|(X)", {
  definitions: {
    "X": {
      validator: "[xX]",
      cardinality: 1,
      casing: "upper"
    }
  }
});
```

or

```
$("selector").inputmask({
  mask: ["99.9", "X"],
  definitions: {
    "X": {
      validator: "[xX]",
      cardinality: 1,
      casing: "upper"
    }
  }
});
```

### Preprocessing masks

[](#preprocessing-masks)

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

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

### JIT Masking

[](#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("date", { jitMasking: true }).mask(selector);
```

Define custom definitions
-------------------------

[](#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)

[](#validatorchrs-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

[](#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 \[pos1, pos2\]
- insert : position(s) to add :

    - { pos : position to insert, c : character to insert }
    - \[{ pos : position to insert, c : character to insert }, { ...}, ... \]
- refreshFromBuffer :

    - true =&gt; refresh validPositions from the complete buffer
    - { start: , end: } =&gt; refresh from start to end

### cardinality

[](#cardinality)

Cardinality specifies how many characters are represented and validated for the definition.

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

[](#prevalidatorchrs-maskset-pos-strict-opts)

The prevalidator option is used to validate the characters before the definition cardinality is reached. (see 'j' example)

### definitionSymbol

[](#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: "[12]", cardinality: 1 },
      { validator: "(19|20)", cardinality: 2 },
      { validator: "(19|20)\\d", cardinality: 3 }
    ]
  },
  'x': {
    validator: "[0-2]",
    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[0-5]|[01][0-9]");
      return valExp2.test(buffer[pos - 1] + chrs);
    },
    cardinality: 1,
    definitionSymbol: "i"
  },
  'z': {
    validator: function (chrs, buffer, pos, strict, opts) {
      var valExp3 = new RegExp("25[0-5]|2[0-4][0-9]|[01][0-9][0-9]");
      return valExp3.test(buffer[pos - 2] + buffer[pos - 1] + chrs);
    },
    cardinality: 1,
    definitionSymbol: "i"
  }
});
```

### placeholder

[](#placeholder)

Specify a placeholder for a definition. This can also be a function.

### set defaults

[](#set-defaults)

Defaults can be set as below.

```
Inputmask.extendDefaults({
  'autoUnmask': true
});
Inputmask.extendDefinitions({
  'A': {
    validator: "[A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]",
    cardinality: 1,
    casing: "upper" //auto uppercasing
  },
  '+': {
    validator: "[0-9A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]",
    cardinality: 1,
    casing: "upper"
  }
});
Inputmask.extendAliases({
  'numeric': {
    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')
    }
  }
});
```

Methods:
--------

[](#methods)

### mask(elems)

[](#maskelems)

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

[](#unmaskedvalue)

Get the `unmaskedvalue`

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

or

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

#### Value unmasking

[](#value-unmasking)

Unmask a given value against the mask.

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

### remove

[](#remove)

Remove the `inputmask`.

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

or

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

or

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

### getemptymask

[](#getemptymask)

return the default (empty) mask value

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

### hasMaskedValue

[](#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

[](#iscomplete)

Verify whether the current value is complete or not.

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

### getmetadata

[](#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

[](#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 in that case. The setvalue functionality does this for you.

### option(options, noremask)

[](#optionoptions-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);
  }
})
```

### format

[](#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"});
```

### isValid

[](#isvalid)

Validate a given value against the mask.

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

Options:
--------

[](#options)

### placeholder

[](#placeholder-1)

Change the mask placeholder. Default: "\_"

Instead of "\_", you can change the unfilled characters mask as you like, simply by adding the `placeholder` option.
For example, `placeholder: " "` will change the default autofill with empty values

```
$(document).ready(function(){
  $("#date").inputmask("99/99/9999",{ "placeholder": "*" });
});
```

or a multi-char placeholder

```
$(document).ready(function(){
  $("#date").inputmask("99/99/9999",{ "placeholder": "dd/mm/yyyy" });
});
```

### optionalmarker

[](#optionalmarker)

Definition of the symbols used to indicate an optional part in the mask.

```
optionalmarker: { start: "[", end: "]" }
```

### quantifiermarker

[](#quantifiermarker)

Definition of the symbols used to indicate a quantifier in the mask.

```
quantifiermarker: { start: "{", end: "}" }
```

### groupmarker

[](#groupmarker)

Definition of the symbols used to indicate a group in the mask.

```
groupmarker: { start: "(", end: ")" }
```

### alternatormarker

[](#alternatormarker)

Definition of the symbols used to indicate an alternator part in the mask.

```
alternatormarker: "|"
```

### escapeChar

[](#escapechar)

Definition of the symbols used to escape a part in the mask.

```
escapeChar: "\\"
```

See **escape special mask chars**

### mask

[](#mask)

The mask to use.

### oncomplete

[](#oncomplete)

Execute a function when the mask is completed

```
$(document).ready(function(){
  $("#date").inputmask("99/99/9999",{ "oncomplete": function(){ alert('inputmask complete'); } });
});
```

### onincomplete

[](#onincomplete)

Execute a function when the mask is incomplete. Executes on blur.

```
$(document).ready(function(){
  $("#date").inputmask("99/99/9999",{ "onincomplete": function(){ alert('inputmask incomplete'); } });
});
```

### oncleared

[](#oncleared)

Execute a function when the mask is cleared.

```
$(document).ready(function(){
  $("#date").inputmask("99/99/9999",{ "oncleared": function(){ alert('inputmask cleared'); } });
});
```

### repeat

[](#repeat)

Mask repeat function. Repeat the mask definition x-times.

```
$(document).ready(function(){
  $("#number").inputmask({ "mask": "9", "repeat": 10 });  // ~ mask "9999999999"
});
```

### greedy

[](#greedy)

Toggle to allocate as much possible or the opposite. Non-greedy repeat function.

```
$(document).ready(function(){
  $("#number").inputmask({ "mask": "9", "repeat": 10, "greedy": false });  // ~ mask "9" or mask "99" or ... mask "9999999999"
});
```

With the non-greedy option set to false, you can specify \* as repeat. This makes an endless repeat.

### autoUnmask

[](#autounmask)

Automatically unmask the value when retrieved.
Default: false.

**When setting this option to true the plugin also expects the initial value from the server to be unmasked.**

### removeMaskOnSubmit

[](#removemaskonsubmit)

Remove the mask before submitting the form.
Default: false

### clearMaskOnLostFocus

[](#clearmaskonlostfocus)

Remove the empty mask on blur or when not empty removes the optional trailing part Default: true

```
$(document).ready(function(){
  $("#ssn").inputmask("999-99-9999",{placeholder:" ", clearMaskOnLostFocus: true }); //default
});
```

### insertMode

[](#insertmode)

Toggle to insert or overwrite input.
Default: true.
This option can be altered by pressing the Insert key.

### clearIncomplete

[](#clearincomplete)

Clear the incomplete input on blur

```
$(document).ready(function(){
  $("#date").inputmask("99/99/9999",{ "clearIncomplete": true });
});
```

### aliases

[](#aliases)

Definitions of aliases.

With an alias you can define a complex mask definition and call it by using an alias name. So this is mainly to simplify the use of your masks. Some aliases found in the extensions are: email, currency, decimal, integer, date, datetime, dd/mm/yyyy, etc.

First you have to create an alias definition. The alias definition can contain options for the mask, custom definitions, the mask to use etc.

When you pass in an alias, the alias is first resolved and then the other options are applied. So you can call an alias and pass another mask to be applied over the alias. This also means that you can write aliases which "inherit" from another alias.

Some examples can be found in jquery.inputmask.xxx.extensions.js

use:

```
$("#date").inputmask("date");
```

or

```
$("#date").inputmask({ alias: "date"});
```

You can also call an alias and extend it with some more options

```
$("#date").inputmask("date", { "clearIncomplete": true });
```

or

```
$("#date").inputmask({ alias: "date", "clearIncomplete": true });
```

### alias

[](#alias)

The alias to use.

```
$("#date").inputmask({ alias: "email"});
```

### onKeyDown

[](#onkeydown)

Callback to implement autocomplete on certain keys for example

Function arguments: event, buffer, caretPos, opts
Function return:

### onBeforeMask

[](#onbeforemask)

Executes before masking the initial value to allow preprocessing of the initial value.

Function arguments: initialValue, opts
Function return: processedValue

```
$(selector).inputmask({
  alias: 'phonebe',
  onBeforeMask: function (value, opts) {
    var processedValue = value.replace(/^0/g, "");
    if (processedValue.indexOf("32") > 1 ||     processedValue.indexOf("32") == -1) {
      processedValue = "32" + processedValue;
    }

    return processedValue;
  }
});
```

### onBeforePaste

[](#onbeforepaste)

This callback allows for preprocessing the pasted value before actually handling the value for masking. This can be usefull for stripping away some characters before processing.

Function arguments: pastedValue, opts
Function return: processedValue

```
$(selector).inputmask({
  mask: '9999 9999 9999 9999',
  placeholder: ' ',
  showMaskOnHover: false,
  showMaskOnFocus: false,
  onBeforePaste: function (pastedValue, opts) {
    var processedValue = pastedValue;

    //do something with it

    return processedValue;
  }
});
```

You can also disable pasting a value by returning false in the onBeforePaste call.

Default: Calls the onBeforeMask

### onBeforeWrite

[](#onbeforewrite)

Executes before writing to the masked element

Use this to do some extra processing of the input. This can be usefull when implementing an alias, ex. decimal alias, autofill the digits when leaving the inputfield.

Function arguments: event, buffer, caretPos, opts
Function return: command object (see Define custom definitions)

### onUnMask

[](#onunmask)

Executes after unmasking to allow post-processing of the unmaskedvalue.

Function arguments: maskedValue, unmaskedValue
Function return: processedValue

```
$(document).ready(function(){
  $("#number").inputmask("decimal", { onUnMask: function(maskedValue, unmaskedValue) {
    //do something with the value
    return unmaskedValue;
  }});
});
```

### showMaskOnFocus

[](#showmaskonfocus)

Shows the mask when the input gets focus. (default = true)

```
$(document).ready(function(){
  $("#ssn").inputmask("999-99-9999",{ showMaskOnFocus: true }); //default
});
```

To make sure no mask is visible on focus also set the showMaskOnHover to false. Otherwise hovering with the mouse will set the mask and will stay on focus.

### showMaskOnHover

[](#showmaskonhover)

Shows the mask when hovering the mouse. (default = true)

```
$(document).ready(function(){
  $("#ssn").inputmask("999-99-9999",{ showMaskOnHover: true }); //default
});
```

### onKeyValidation

[](#onkeyvalidation)

Callback function is executed on every keyvalidation with the key &amp; result as parameter.

```
$(document).ready(function(){
  $("#ssn").inputmask("999-99-9999", {
    onKeyValidation: function (key, result) {
      console.log(key + " - " + result);
    }
  });
});
```

### skipOptionalPartCharacter

[](#skipoptionalpartcharacter-1)

### numericInput

[](#numericinput)

Numeric input direction. Keeps the caret at the end.

```
$(document).ready(function(){
  $(selector).inputmask('€ 999.999.999,99', { numericInput: true });    //123456  =>  € ___.__1.234,56
});
```

### rightAlign

[](#rightalign)

Align the input to the right

By setting the rightAlign you can specify to right align an inputmask. This is only applied in combination op the numericInput option or the dir-attribute. Default is true.

```
$(document).ready(function(){
  $(selector).inputmask('decimal', { rightAlign: false });  //disables the right alignment of the decimal input
});
```

### undoOnEscape

[](#undoonescape)

Make escape behave like undo. (ctrl-Z)
Pressing escape reverts the value to the value before focus.
Default: true

### radixPoint (numerics)

[](#radixpoint-numerics)

Define the radixpoint (decimal separator)
Default: ""

### groupSeparator (numerics)

[](#groupseparator-numerics)

Define the groupseparator
Default: ""

### keepStatic

[](#keepstatic)

Default: null (~false) Use in combination with the alternator syntax Try to keep the mask static while typing. Decisions to alter the mask will be postponed if possible.

ex. $(selector).inputmask({ mask: \["+55-99-9999-9999", "+55-99-99999-9999", \], keepStatic: true });

typing 1212345123 =&gt; should result in +55-12-1234-5123 type extra 4 =&gt; switch to +55-12-12345-1234

When passing multiple masks (an array of masks) keepStatic is automatically set to true unless explicitly set through the options.

### positionCaretOnTab

[](#positioncaretontab)

When enabled the caret position is set after the latest valid position on TAB Default: true

### tabThrough

[](#tabthrough)

Allows for tabbing through the different parts of the masked field.
Default: false

### definitions

[](#definitions)

### ignorables

[](#ignorables)

### isComplete

[](#iscomplete-1)

With this call-in (hook) you can override the default implementation of the isComplete function.
Args =&gt; buffer, opts Return =&gt; true|false

```
$(selector).inputmask({
  regex: "[0-9]*",
  isComplete: function(buffer, opts) {
    return new RegExp(opts.regex).test(buffer.join(''));
  }
});
```

### canClearPosition

[](#canclearposition)

Hook to alter the clear behavior in the stripValidPositions
Args =&gt; maskset, position, lastValidPosition, opts
Return =&gt; true|false

### postValidation

[](#postvalidation)

Hook to postValidate the result from isValid. Usefull for validating the entry as a whole. Args =&gt; buffer, currentResult, opts
Return =&gt; true|false|command object

### preValidation

[](#prevalidation)

Hook to preValidate the input. Useful for validating regardless the definition. Args =&gt; buffer, pos, char, isSelection, opts =&gt; return true/false/command object When return true, the normal validation kicks in, otherwise it is skipped.

### staticDefinitionSymbol

[](#staticdefinitionsymbol)

The staticDefinitionSymbol option is used to indicate that the static entries in the mask can match a certain definition. Especially usefull with alternators so that static element in the mask can match another alternation.

In the example below we mark the spaces as a possible match for the "i" definition. By doing so the mask can alternate to the second mask even when we typed already "12 3".

```
Inputmask("(99 99 999999)|(i{+})", {
  definitions: {
    "i": {
      validator: ".",
      cardinality: 1,
      definitionSymbol: "*"
    }
  },
  staticDefinitionSymbol: "*"
}).mask(selector);
```

### nullable

[](#nullable)

Return nothing when the user hasn't entered anything. Default: true

### noValuePatching

[](#novaluepatching)

Disable value property patching
Default: false

### positionCaretOnClick

[](#positioncaretonclick)

Positioning of the caret on click. Options none, lvp (based on the last valid position (default), radixFocus (position caret to radixpoint on initial click) Default: "lvp"

### casing

[](#casing)

Apply casing at the mask-level. Options: null, "upper", "lower" or "title"
or callback args =&gt; elem, test, pos, validPositions return charValue

```
casing: function(elem, test, pos, validPositions) {
	do some processing || upper/lower input property in the validPositions
	return elem; //upper/lower element
}

```

Default: null

### inputmode

[](#inputmode)

Default: "verbatim" Specify the inputmode - already in place for when browsers start to support them

### colorMask

[](#colormask)

Default: false Create a css styleable mask. Uses css classes: im-caret, im-static.

You need to include the inputmask.css in your page to use this option in full.

General
-------

[](#general)

### set a value and apply mask

[](#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(){
  $('#').inputmask({ "mask": "99/99/9999", 'autoUnmask' : true});    //  value: 23/03/1973
  alert($('#').val());    // shows 23031973     (autoUnmask: true)

  var tbDate = document.getElementById("");
  alert(tbDate.value);    // shows 23031973     (autoUnmask: true)
});
```

### escape special mask chars

[](#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");
});
```

### auto-casing inputmask

[](#auto-casing-inputmask)

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

```
Inputmask.extendDefinitions({
  'A': {
    validator: "[A-Za-z]",
    cardinality: 1,
    casing: "upper" //auto uppercasing
  },
  '+': {
    validator: "[A-Za-z\u0410-\u044F\u0401\u04510-9]",
    cardinality: 1,
    casing: "upper"
  }
});
```

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

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

Supported markup options
------------------------

[](#supported-markup-options)

### RTL attribute

[](#rtl-attribute)

```

```

### readonly attribute

[](#readonly-attribute)

```

```

### disabled attribute

[](#disabled-attribute)

```

```

### maxlength attribute

[](#maxlength-attribute)

```

```

### data-inputmask attribute

[](#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 {}.

```

```

```
$(document).ready(function(){
  $(":input").inputmask();
});
```

### data-inputmask-&lt;option&gt; attribute

[](#data-inputmask-option-attribute)

All options can also be passed through data-attributes.

```

```

```
$(document).ready(function(){
  $(":input").inputmask();
});
```

jQuery.clone
------------

[](#jqueryclone)

When cloning a inputmask, the inputmask reactivates on the first event (mouseenter, focus, ...) that happens to the input. If you want to set a value on the cloned inputmask and you want to directly reactivate the masking you have to use $(input).inputmask("setvalue", value)

jquery.inputmask extensions
===========================

[](#jqueryinputmask-extensions)

[date &amp; datetime extensions](README_date.md)
------------------------------------------------

[](#date--datetime-extensions)

[numeric extensions](README_numeric.md)
---------------------------------------

[](#numeric-extensions)

[phone extensions](README_phone.md)
-----------------------------------

[](#phone-extensions)

[other extensions](README_other.md)
-----------------------------------

[](#other-extensions)

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance27

Infrequent updates — may be unmaintained

Popularity15

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity83

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 96.9% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~17 days

Recently: every ~23 days

Total

202

Last Release

669d ago

Major Versions

4.0.5 → 5.0.0-beta.912018-12-28

4.0.6 → 5.0.0-beta.1022019-01-30

4.0.7 → 5.0.0-beta.1522019-05-14

4.0.9 → 5.0.0-beta.2802019-10-08

4.x-dev → 5.0.2-beta.72020-01-09

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/86051413?v=4)[Sitnikov-TV](/maintainers/Sitnikov-TV)[@Sitnikov-TV](https://github.com/Sitnikov-TV)

---

Top Contributors

[![RobinHerbots](https://avatars.githubusercontent.com/u/318447?v=4)](https://github.com/RobinHerbots "RobinHerbots (2036 commits)")[![rosshadden](https://avatars.githubusercontent.com/u/669012?v=4)](https://github.com/rosshadden "rosshadden (12 commits)")[![vsn4ik](https://avatars.githubusercontent.com/u/3757319?v=4)](https://github.com/vsn4ik "vsn4ik (6 commits)")[![kgeis](https://avatars.githubusercontent.com/u/2237299?v=4)](https://github.com/kgeis "kgeis (5 commits)")[![SimenB](https://avatars.githubusercontent.com/u/1404810?v=4)](https://github.com/SimenB "SimenB (4 commits)")[![zeskysee](https://avatars.githubusercontent.com/u/6244226?v=4)](https://github.com/zeskysee "zeskysee (3 commits)")[![Rouche](https://avatars.githubusercontent.com/u/1267438?v=4)](https://github.com/Rouche "Rouche (3 commits)")[![OddEssay](https://avatars.githubusercontent.com/u/837227?v=4)](https://github.com/OddEssay "OddEssay (2 commits)")[![andr-04](https://avatars.githubusercontent.com/u/2203770?v=4)](https://github.com/andr-04 "andr-04 (2 commits)")[![dasmfm](https://avatars.githubusercontent.com/u/1413874?v=4)](https://github.com/dasmfm "dasmfm (2 commits)")[![erbridge](https://avatars.githubusercontent.com/u/1027364?v=4)](https://github.com/erbridge "erbridge (2 commits)")[![fquiroz01](https://avatars.githubusercontent.com/u/9734881?v=4)](https://github.com/fquiroz01 "fquiroz01 (2 commits)")[![larmic](https://avatars.githubusercontent.com/u/1371298?v=4)](https://github.com/larmic "larmic (2 commits)")[![ajacome](https://avatars.githubusercontent.com/u/7635259?v=4)](https://github.com/ajacome "ajacome (2 commits)")[![VladimirKuzmin](https://avatars.githubusercontent.com/u/2759192?v=4)](https://github.com/VladimirKuzmin "VladimirKuzmin (2 commits)")[![whooehoo](https://avatars.githubusercontent.com/u/11571567?v=4)](https://github.com/whooehoo "whooehoo (2 commits)")[![pgs-tmikus](https://avatars.githubusercontent.com/u/4981727?v=4)](https://github.com/pgs-tmikus "pgs-tmikus (1 commits)")[![mhlavacek](https://avatars.githubusercontent.com/u/624597?v=4)](https://github.com/mhlavacek "mhlavacek (1 commits)")[![marnen](https://avatars.githubusercontent.com/u/34378?v=4)](https://github.com/marnen "marnen (1 commits)")[![gubi](https://avatars.githubusercontent.com/u/746559?v=4)](https://github.com/gubi "gubi (1 commits)")

---

Tags

jquerypluginsforminputmaskinputmask

### Embed Badge

![Health badge](/badges/sgu-infocom-official-inputmask-v3311/health.svg)

```
[![Health](https://phpackages.com/badges/sgu-infocom-official-inputmask-v3311/health.svg)](https://phpackages.com/packages/sgu-infocom-official-inputmask-v3311)
```

###  Alternatives

[robinherbots/jquery.inputmask

Inputmask is a javascript library which creates an input mask. Inputmask can run against vanilla javascript, jQuery and jqlite.

6.5k284.5k4](/packages/robinherbots-jqueryinputmask)[snapappointments/bootstrap-select

The jQuery plugin that brings select elements into the 21st century with intuitive multiselection, searching, and much more. Now with Bootstrap 4 support.

9.8k501.2k3](/packages/snapappointments-bootstrap-select)[kartik-v/yii2-widget-rating

A Yii2 widget for the simple yet powerful bootstrap-star-rating plugin with fractional rating support (sub repo split from yii2-widgets)

474.3M8](/packages/kartik-v-yii2-widget-rating)[kartik-v/yii2-widget-switchinput

A Yii2 wrapper widget for the Bootstrap Switch plugin to use checkboxes &amp; radios as toggle switchinputes (sub repo split from yii2-widgets)

384.6M13](/packages/kartik-v-yii2-widget-switchinput)[kartik-v/yii2-widget-colorinput

An enhanced Yii 2 widget encapsulating the HTML 5 color input (sub repo split from yii2-widgets)

345.1M12](/packages/kartik-v-yii2-widget-colorinput)[kartik-v/yii2-widget-rangeinput

An enhanced Yii 2 widget encapsulating the HTML 5 range input (sub repo split from yii2-widgets)

214.1M3](/packages/kartik-v-yii2-widget-rangeinput)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
