Security News
Weekly Downloads Now Available in npm Package Search Results
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
jquery.inputmask
Advanced tools
#jquery.inputmask 3.x
Copyright (c) 2010 - 2014 Robin Herbots Licensed under the MIT license (http://opensource.org/licenses/mit-license.php)
jquery.inputmask is a jQuery plugin which create an input mask.
An inputmask helps the user with the input by ensuring a predefined format. This can be useful for dates, numerics, phone numbers, ...
Highlights:
Demo page see http://robinherbots.github.io/jquery.inputmask
Include the js-files which you can find in the dist-folder. You have the bundled file which contains the main plugin code and also all extensions (date, numerics, other) or if you prefer to only include some parts, use the separate js-files in the dist/min folder.
The minimum to include is the jquery.inputmask.js
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.inputmask.js" type="text/javascript"></script>
Define your masks:
$(document).ready(function(){
$(selector).inputmask("99-9999999"); //static mask
$(selector).inputmask("mask", {"mask": "(999) 999-9999"}); //specifying fn & options
$(selector).inputmask({"mask": "99-9999999"}); //specifying options only
$(selector).inputmask("9-a{1,3}9{1,3}"); //mask with dynamic syntax
});
or via data-inputmask attribute
<input data-inputmask="'alias': 'date'" />
<input data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false" />
<input data-inputmask="'mask': '99-9999999'" />
$(document).ready(function(){
$(":input").inputmask();
});
Any option can also be passed through the use of a data attribute. Use data-inputmask-<the name op the option>="value"
<input id="example1" data-inputmask-clearmaskonlostfocus="false" />
<input id="example2" data-inputmask-regex="[a-za-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?" />
$(document).ready(function(){
$("#example1").inputmask("99-9999999");
$("#example2").inputmask("Regex");
});
There are more definitions defined within the extensions.
You can find info within the js-files or by further exploring the options.
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
});
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 => 12123451234 mask => (12) 12345-1234 (trigger complete)
Input => 121234-1234 mask => (12) 1234-1234 (trigger complete)
Input => 1212341234 mask => (12) 12341-234_ (trigger incomplete)
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 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
.
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: "99999[-9999]", greedy: false });
The initial mask shown will be "" instead of "-____".
Dynamic masks can change during the input. To define a dynamic part use { }.
{n} => n repeats
{n,m} => 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"
}
}
});
TODO - explain
$("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"
}
}
});
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"]; }});
You can define your own definitions to use in your mask.
Start by choosing a masksymbol.
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.
Cardinality specifies how many characters are represented and validated for the definition.
The prevalidator option is used to validate the characters before the definition cardinality is reached. (see 'j' example)
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)
$.extend($.inputmask.defaults.definitions, {
'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"
}
});
Specify a placeholder for a definition.
$.extend($.inputmask.defaults, {
'autoUnmask': true
});
Change the mask placeholder
$(document).ready(function(){
$("#date").inputmask("d/m/y",{ "placeholder": "*" });
});
or a multi-char placeholder
$(document).ready(function(){
$("#date").inputmask("d/m/y",{ "placeholder": "dd/mm/yyyy" });
});
Execute a function when the mask is completed
$(document).ready(function(){
$("#date").inputmask("d/m/y",{ "oncomplete": function(){ alert('inputmask complete'); } });
});
Execute a function when the mask is incomplete. Executes on blur.
$(document).ready(function(){
$("#date").inputmask("d/m/y",{ "onincomplete": function(){ alert('inputmask incomplete'); } });
});
Execute a function when the mask is cleared.
$(document).ready(function(){
$("#date").inputmask("d/m/y",{ "oncleared": function(){ alert('inputmask cleared'); } });
});
Mask repeat function. Repeat the mask definition x-times.
$(document).ready(function(){
$("#number").inputmask({ "mask": "9", "repeat": 10 }); // ~ mask "9999999999"
});
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.
Remove the mask before submitting the form. Use in combination with autoUnmask: true
Remove the empty mask on blur or when not empty removes the optional trailing part
$(document).ready(function(){
$("#ssn").inputmask("999-99-9999",{placeholder:" ", clearMaskOnLostFocus: true }); //default
});
Clear the incomplete input on blur
$(document).ready(function(){
$("#date").inputmask("d/m/y",{ "clearIncomplete": true } });
});
//ADD better explanation
First you have to create an alias definition (more examples can be found in jquery.inputmask.extensions.js)
$.extend($.inputmask.defaults.aliases, {
'date': {
mask: "d/m/y"
},
'dd/mm/yyyy': {
alias: "date"
}
});
use:
$(document).ready(function(){
$("#date").inputmask("date"); // => equals to $("#date").inputmask("d/m/y");
});
or use the dd/mm/yyyy alias of the date alias:
$(document).ready(function(){
$("#date").inputmask("dd/mm/yyyy"); // => equals to $("#date").inputmask("d/m/y");
});
Executes after unmasking to allow post-processing of the unmaskedvalue. The arguments to the function are maskedValue, unmaskedValue.
$(document).ready(function(){
$("#number").inputmask("decimal", { onUnMask: function(maskedValue, unmaskedValue) {
//do something with the value
return unmaskedValue;
}});
});
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.
Shows the mask when hovering the mouse. (default = true)
$(document).ready(function(){
$("#ssn").inputmask("999-99-9999",{ showMaskOnHover: true }); //default
});
Callback function is executed on every keyvalidation with the result as parameter.
$(document).ready(function(){
$("#ssn").inputmask("999-99-9999",
{ onKeyValidation: function (result) {
console.log(result);
} });
});
Show the current mask definition as a tooltip.
$(selector).inputmask({ mask: ["999-999-9999 [x99999]", "+099 99 99 9999[9]-9999"], showTooltip: true });
Numeric input direction. Keeps the caret at the end.
$(document).ready(function(){
$(selector).inputmask('€ 999.999.999,99', { numericInput: true }); //123456 => € ___.__1.234,56
});
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
});
Default: undefined (~false)
Use in combination with the alternator syntax
Try to keep the mask static while typing. Decisions to alter the mask will be posponed if possible.
ex. $(selector).inputmask({ mask: ["+55-99-9999-9999", "+55-99-99999-9999", ], keepStatic: true });
typing 1212345123 => should result in +55-12-1234-5123 type extra 4 => 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.
With this call-in you can override the default implementation of the isComplete function.
Args => buffer, opts
Return => true || false
$(selector).inputmask("Regex", {
regex: "[0-9]*",
isComplete: function(buffer, opts) {
return new RegExp(opts.regex).test(buffer.join(''));
}
});
##Functions
Get the unmaskedvalue
$(document).ready(function(){
$(selector).inputmask('unmaskedvalue');
});
Remove the inputmask.
$(document).ready(function(){
$(selector).inputmask('remove');
});
Verify whether the current value is complete or not.
$(document).ready(function(){
if($(selector).inputmask("isComplete")){
//do something
}
});
Only applies on multi-masks. The metadata of the actual mask provided in the mask definitions can be obtained by calling
$(selector).inputmask("getmetadata");
##General
this can be done with the traditional jquery.val function (all browsers) or JavaScript value property for browsers which implement lookupGetter or getOwnPropertyDescriptor
$(document).ready(function(){
$("#number").val(12345);
var number = document.getElementById("number");
number.value = 12345;
});
with the autoUnmaskoption you can change the return of $.fn.val (or value property) to unmaskedvalue or the maskedvalue
$(document).ready(function(){
$('#<%= tbDate.ClientID%>').inputmask({ "mask": "d/m/y", 'autoUnmask' : true}); // value: 23/03/1973
alert($('#<%= tbDate.ClientID%>').val()); // shows 23031973 (autoUnmask: true)
var tbDate = document.getElementById("<%= tbDate.ClientID%>");
alert(tbDate.value); // shows 23031973 (autoUnmask: true)
});
$(document).ready(function(){
$("#months").inputmask("m \\months");
});
You can define within a definition to automatically lowercase or uppercase the entry in an input by giving the casing.
Casing can be null, "upper" or "lower"
$.extend($.inputmask.defaults.definitions, {
'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
});
<input id="test" dir="rtl" />
<input id="test" readonly="readonly" />
<input id="test" disabled="disabled" />
<input id="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 {}.
<input data-inputmask="'alias': 'date'" />
<input data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false" />
$(document).ready(function(){
$(":input").inputmask();
});
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();
});
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"});
Validate a given value against the mask.
var isValid = $.inputmask.isValid("23/03/1973", { alias: "dd/mm/yyyy"});
First grab the sources from GitHub. In the root you type ant. A new folder dist is created with the minified and optimized js-files
PM> Install-Package jQuery.InputMask
In App_Start, BundleConfig.cs
bundles.Add(new ScriptBundle("~/bundles/inputmask").Include(
"~/Scripts/jquery.inputmask/jquery.inputmask-{version}.js",
"~/Scripts/jquery.inputmask/jquery.inputmask.extensions-{version}.js",
"~/Scripts/jquery.inputmask/jquery.inputmask.date.extensions-{version}.js",
"~/Scripts/jquery.inputmask/jquery.inputmask.numeric.extensions-{version}.js"));
In Layout
@Scripts.Render("~/bundles/inputmask")
#=========== TODO ===========
return the default (empty) mask value
$(document).ready(function(){
$("#test").inputmask("999-AAA");
var initialValue = $("#test").inputmask("getemptymask"); // initialValue => "___-___"
});
Use this to do some extra processing of the input when certain keys are pressed. This can be usefull when implementing an alias, ex. decimal alias, autofill the digits when pressing tab.
see jquery.inputmask.extensions.js for some examples
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.
$(document).ready(function(){
$("#test").inputmask("99.", {
repeat: 4,
onBeforePaste: function (pastedValue) {
//do somehing with the value
return pastedValue;
}
});
});
This callback allows for preprocessing the initial value before actually handling the value for masking. This can be usefull for stripping away some characters before processing.
$(document).ready(function(){
$("#test").inputmask("99.", {
repeat: 4,
onBeforeMask: function (initialValue) {
//do somehing with the value
return initialValue;
}
});
});
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);
});
$(document).ready(function(){
$(selector).inputmask("dd/mm/yyyy");
$(selector).inputmask("mm/dd/yyyy");
$(selector).inputmask("date"); // alias for dd/mm/yyyy
$(selector).inputmask("date", {yearrange: { minyear: 1900, maxyear: 2099 }}); //specify year range
});
The date aliases take leap years 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(){
$(selector).inputmask("datetime"); // 24h
$(selector).inputmask("datetime12"); // am/pm
});
$(document).ready(function(){
$(selector).inputmask("decimal");
$(selector).inputmask("decimal", { allowMinus: false });
$(selector).inputmask("integer");
});
Define the radixpoint
$(document).ready(function(){
$(selector).inputmask("decimal", { radixPoint: "," });
});
Define the number of digits after the radixpoint
$(document).ready(function(){
$(selector).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(){
$(selector).inputmask("decimal", { radixPoint: ",", autoGroup: true, groupSeparator: ".", groupSize: 3 });
});
Allow minus and/or plus symbol
$(document).ready(function(){
$(selector).inputmask("decimal", { allowMinus: false });
$(selector).inputmask("integer", { allowMinus: false, allowPlus: true });
});
With the regex extension you can use any regular expression as a mask. Currently this does only input restriction.
There is no further masking visualization.
Example simple email regex:
$(document).ready(function(){
$(selector).inputmask('Regex', { regex: "[a-zA-Z0-9._%-]+@[a-zA-Z0-9-]+\\.[a-zA-Z]{2,4}" });
});
Uses the phone mask definitions from https://github.com/andr-04/inputmask-multi
$(selector).inputmask("phone", {
url: "Scripts/jquery.inputmask/phone-codes/phone-codes.json",
onKeyValidation: function () { //show some metadata in the console
console.log($(this).inputmask("getmetadata")["name_en"]);
}
});
An ip address alias for entering valid ip-addresses.
$(document).ready(function(){
$(selector).inputmask("ip");
});
You can find/modify/extend this alias in the jquery.inputmask.extensions.js
FAQs
jquery.inputmask is a jquery plugin which create an input mask.
The npm package jquery.inputmask receives a total of 8,298 weekly downloads. As such, jquery.inputmask popularity was classified as popular.
We found that jquery.inputmask demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
Security News
A Stanford study reveals 9.5% of engineers contribute almost nothing, costing tech $90B annually, with remote work fueling the rise of "ghost engineers."
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.