jquery.inputmask 输入框input输入内容格式限制插件
jQuery Input Mask plugin
http://robinherbots.github.io/jquery.inputmask
README.md
jquery.inputmask
Copyright (c) 2010 - 2013 Robin Herbots Licensed under the MIT license (http://www.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:
- 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
 - multi-mask support
 - regex-mask support
 
Demo page see http://robinherbots.github.io/jquery.inputmask
Usage:
Include the js-files which you can find in the dist-folder. You have the bundled file which contains the main plugin code and also all extensions. (date, numerics, other) or if you prefer to only include some parts, use the separate js-files in the dist/min folder.
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(){
   $("#date").inputmask("d/m/y");  //direct mask
   $("#phone").inputmask("mask", {"mask": "(999) 999-9999"}); //specifying fn & options
   $("#tin").inputmask({"mask": "99-9999999"}); //specifying options only
});
or
<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();
});
Default masking definitions
- 9 : numeric
 - a : alphabetic
 - * : alphanumeric
 
There are more definitions defined within the extensions. 
You can find info within the js-files or by further exploring the options.
Options:
change the 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, incomplete or cleared
$(document).ready(function(){
   $("#date").inputmask("d/m/y",{ "oncomplete": function(){ alert('inputmask complete'); } });
   $("#date").inputmask("d/m/y",{ "onincomplete": function(){ alert('inputmask incomplete'); } });
   $("#date").inputmask("d/m/y",{ "oncleared": function(){ alert('inputmask cleared'); } });
});
clearIncomplete - clear the incomplete input on blur
$(document).ready(function(){
   $("#date").inputmask("d/m/y",{ "clearIncomplete": true } });
});
mask repeat function
$(document).ready(function(){
   $("#number").inputmask({ "mask": "9", "repeat": 10 });  // ~ mask "9999999999"
});
mask 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.
get the unmaskedvalue
$(document).ready(function(){
   $("#number").inputmask('unmaskedvalue');
});
set a value and apply mask
this can be done with the traditionnal 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)
});
add custom definitions
You can define your own definitions to use in your mask. 
Start by choosing a masksymbol.
validator
Next define your validator. The validator can be a regular expression or a function.
cardinality
Cardinality specifies how many characters are represented and validated for the definition.
prevalidator
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 characteres 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"
      }
});
set defaults
$.extend($.inputmask.defaults, {
    'autoUnmask': true
});
numeric input direction
$(document).ready(function(){
    $(selector).inputmask('€ 999.999.999,99', { numericInput: true });    //123456  =>  € ___.__1.234,56
});
skipRadixDance
If you define a radixPoint the caret will always jump to the integer part, until you type the radixpoint.
$(document).ready(function(){
    $(selector).inputmask('€ 999.999.999,99', { numericInput: true, radixPoint: "," });
});
This behavior can be skipped by setting the skipRadixDance to true.
align the numerics to the right
By setting the rightAlignNumerics you can specify to right align a numeric inputmask. Default is true.
$(document).ready(function(){
    $(selector).inputmask('decimal', { rightAlignNumerics: false });  //disables the right alignment of the decimal input
});
remove the inputmask
$(document).ready(function(){
    $('selector').inputmask('remove');
});
escape special mask chars
$(document).ready(function(){
    $("#months").inputmask("m \\months");
});
clearMaskOnLostFocus
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
});
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 => 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 clearMaskOnLostFocus: true is set in the options (default), the mask will clearout 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
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 "_____-____".
Multiple masks
You can define multiple mask for your input. Depending on the input the masking will switch between the defined masks. 
This can be usefull when the masks are too different to solve it with optional parts.
  $(selector).inputmask({ mask: ["999.999", "aa-aa-aa"]});
inputmask-multi format
You can also pass an array for masking with the a format alike the format used in inputmask-multi
var phones = [
{ "mask": "+247-####", "cc": "AC", "name_en": "Ascension", "desc_en": "", "name_ru": "Остров Вознесения", "desc_ru": "" },
{ "mask": "+376-###-###", "cc": "AD", "name_en": "Andorra", "desc_en": "", "name_ru": "Андорра", "desc_ru": "" },
{ "mask": "+971-5#-###-####", "cc": "AE", "name_en": "United Arab Emirates", "desc_en": "mobile", "name_ru": "Объединенные Арабские Эмираты", "desc_ru": "мобильные" },
...
]
$(selector).inputmask({ mask: phones, definitions: { '#': { validator: "[0-9]", cardinality: 1}} }); //in case of inputmask-multi you need to specify the validator for #
The metadata of the actual mask provided in the mask definitions can be obtained by calling
$(selector).inputmask("getmetadata");
Preprocessing mask
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"]; }});
aliases option
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");
});
auto upper/lower- casing inputmask
You can define whitin 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
});
getemptymask command
return the default (empty) mask value
$(document).ready(function(){
   $("#test").inputmask("999-AAA");
   var initialValue = $("#test").inputmask("getemptymask");  // initialValue  => "___-___"
});
onKeyUp / onKeyDown option
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
hasMaskedValue
Check wheter the returned value is masked or not; currently only works reliable 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);
});
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
Shows the mask when hovering the mouse. (default = true)
$(document).ready(function(){
    $("#ssn").inputmask("999-99-9999",{ showMaskOnHover: true }); //default
});
onKeyValidation
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);
                                } });
});
isComplete
Verify wheter the current value is complete or not.
$(document).ready(function(){
    if($("#ssn").inputmask("isComplete")){
        //do something
    }
});
showTooltip
Show the current mask definition as a tooltip.
  $(selector).inputmask({ mask: ["999-999-9999 [x99999]", "+099 99 99 9999[9]-9999"], showTooltip: true });
Supported markup options
RTL attribute
<input id="test" dir="rtl" />
readonly attribute
<input id="test" readonly="readonly" />
disabled attribute
<input id="test" disabled="disabled" />
maxlength attribute
<input id="test" maxlength="4" />
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 welformed json-string without the {}.
<input data-inputmask="'alias': 'date'" />
<input data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false" />
$(document).ready(function(){
    $(":input").inputmask();
});
Compiling with Google Closure Compiler
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
.NET Nuget Package Install
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")
jquery.inputmask extensions
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
});
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 });
});
regex extensions
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(){
   $("#numeric").inputmask('Regex', { regex: "[a-zA-Z0-9._%-]+@[a-zA-Z0-9-]+\\.[a-zA-Z]{2,4}" });
});
phone extensions
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"]);
                }
  });
other extensions
An ip adress alias for entering valid ip-addresses.
$(document).ready(function(){
   $(selector).inputmask("ip");
});
You can find/modify/extend this alias in the jquery.inputmask.extensions.js
External links
https://github.com/andr-04/inputmask-multi 
https://github.com/greengerong/green.inputmask4angular
jquery.inputmask 输入框input输入内容格式限制插件的更多相关文章
- jquery.inputmask.js 输入框input输入内容格式限制插件
		
今天使用的就是这几行代码. 利用 jquery.inputmask.js 下载地址(如果打不开的话 请FQ http://plugins.jquery.com/jquery.inputmask/) ...
 - 实时监听input输入内容的N种方法
		
现在有一个需求,需要我们实时监听input输入框中的内容,从而带来更好的用户体验,而不是等我们全部输入完毕才告诉我们格式不对首先我们创建一个input输入框 <form name='loginF ...
 - 类似智能购票的demo--进入页面后默认焦点在第一个输入框,输入内容、回车、right时焦点自动跳到下一个,当跳到select时,下拉选项自动弹出,并且可以按上下键选择,选择完成后再跳到下一个。
		
要实现的效果:进入页面后默认焦点在第一个输入框,输入内容.回车.right时焦点自动跳到下一个,当跳到select时,下拉选项自动弹出,并且可以按上下键选择,选择完成后再跳到下一个. PS:自己模拟的 ...
 - 正则表达式控制Input输入内容 ,js正则验证方法大全
		
https://blog.csdn.net/xushichang/article/details/4041507 //输入姓名的正则校验 e.currentTarget.value = e.curre ...
 - Python+Selenium自动化-清空输入框、输入内容、点击按钮
		
Python+Selenium自动化-清空输入框.输入内容.点击按钮 1.输入内容 send_keys('valve'):输入内容valve #定位输入框 input_box = browser. ...
 - input实时监听控制输入框的输入内容和长度,并进行提示和反馈
		
一.前言 在MVVM模式下,有个双向数据绑定(data-binding)的优势,可以通过viewmodel实时的监听用户操作,也可以将model的改动实时的反馈到界面上. 那么,在传统的js操控DOM ...
 - 一个input输入内容监听联动的demo
		
两个input,一个在其中一个输入,内容在另一个input中实时回显 代码如下 <!DOCTYPE html> <html> <head> <title> ...
 - 关于隐藏input输入内容问题
		
如果想通过获取焦点输入改变内容,type不能是hidden的 <input type="hidden" id="test"> // 这种是不行的,只 ...
 - 限制<input>输入内容 只允许数字 或者 字母
		
只能输入数字: 有回显 <input onkeyup="value=value.replace(/[^\d]/g,'')"> 只能输入数字:无回显 <input ...
 
随机推荐
- 前后端协调处理checkbox
			
需求:页面属于一个弹出窗体,查询结果,用checkbox展示,选择后,把选中的结果传递给调用页面. 由于要取得后端写的checkbox控件的值,所以在后端处理最后的提交事件,用这个语句把结果传递到页面 ...
 - [Angular] Communicate with Angular Elements using Inputs and Events
			
In a real world scenario we obviously need to be able to communicate with an Angular Element embedde ...
 - 启动IntelliJ IDEA 2016报错:cannot start under Java 1.7 : Java 1.8 or later is required 解决办法
			
idea64.exe启动错误:Cannot start under Java 1.7.0xxx IntelliJ IDEA : Unsupported java version Cannot star ...
 - OpenGL ES 3.0片段着色器(四)
			
片段着色器流程图 片段着色器(fragment shader)实现了一个通用的可编程操作片段的方法.片段着色器执行由 光栅化生成的每个片段. • Shader program(着色器程序)—片段着色器 ...
 - Virtualbox安装Ubuntu
			
每次安装虚拟机都是总要折腾一下,毕竟不是特别熟悉,几个小细节总要google半天,为了以后能愉快的玩耍.把这些问题都记录下来,免得再折腾. 此文档都来自其他人的文章,我保存在Evernote整理. 网 ...
 - DexHunter脱壳神器分析
			
0x00 这篇文章我们分析Android脱壳神器DexHunter的源码. DexHunter作者也写了一篇介绍它的文章从Android执行时出发.打造我们的脱壳神器.DexHunter源码位于htt ...
 - iOS编程(双语版) - 视图 - 手工代码(不使用向导)创建视图
			
如何创建一个空的项目,最早的时候XCode的项目想到中,还有Empty Application template这个选项,后来Apple把它 给去掉了. 我们创建一个单视图项目. 1) 删除main. ...
 - 【树莓派】使用xdrp远程登录树莓派的图形界面
			
之前采用了vnc方式方式的树莓派,但是配置还有点步骤,刚才看了一下,试验了一下xrdp,直接很简单就好了. 树莓派DIY笔记之前有介绍过用VNC连接到树莓派的方法.在Windows下,当然还是自带的远 ...
 - Linux中使用GoAccess进行日志实时监控
			
一.用法命令: goaccess access_log -o /var/www/html/report.html --real-time-html 说明:请先安装Httpd和Goaccess 二.效果 ...
 - Python 字典(联合内存、联合数组)
			
字典 Python有一个内建数据类型是字典(Dictionaries).字典在某些语言中可能称为“联合内存”("associative memories'')或“联合数组”("as ...