hjg
2024-07-09 30304784e82d4bba24121328da8eb8490aec4f4f
提交 | 用户 | 时间
58d006 1 #jquery.inputmask
A 2
3 Copyright (c) 2010 - 2013 Robin Herbots
4 Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
5
6 jquery.inputmask is a jquery plugin which create an input mask.
7
8 An inputmask helps the user with the input by ensuring a predefined format. This can be usefull for dates, numerics, phone numbers, ...
9
10 Highlights:
11 - easy to use
12 - optional parts anywere in the mask
13 - possibility to define aliases which hide complexity
14 - date / datetime masks
15 - numeric masks
16 - lots of callbacks
17 - non-greedy masks
18 - many features can be enabled/disabled/configured by options
19 - supports readonly/disabled/dir="rtl" attributes
20 - support data-inputmask attribute  
21 - multi-mask support  
22
23
24 ## Usage:
25
26 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.
27
28 The minimum to include is the jquery.inputmask.js
29
30 ```html
31 <script src="jquery.js" type="text/javascript"></script>
32 <script src="jquery.inputmask.js" type="text/javascript"></script>
33 ```
34
35 Define your masks:
36
37 ```javascript
38 $(document).ready(function(){
39    $("#date").inputmask("d/m/y");  //direct mask
40    $("#phone").inputmask("mask", {"mask": "(999) 999-9999"}); //specifying fn & options
41    $("#tin").inputmask({"mask": "99-9999999"}); //specifying options only
42 });
43 ```
44
45 or
46
47 ```html
48 <input data-inputmask="'alias': 'date'" />
49 <input data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false" />
50 <input data-inputmask="'mask': '99-9999999'" />
51 ```
52 ```javascript
53 $(document).ready(function(){
54     $(":input").inputmask();
55 });
56 ```
57
58 ## Options:
59
60 ### change the placeholder
61
62
63 ```javascript
64 $(document).ready(function(){
65    $("#date").inputmask("d/m/y",{ "placeholder": "*" });
66 });
67 ```
68
69 or a multi-char placeholder
70
71 ```javascript
72 $(document).ready(function(){
73    $("#date").inputmask("d/m/y",{ "placeholder": "dd/mm/yyyy" });
74 });
75 ```
76
77 ### execute a function when the mask is completed, incomplete or cleared
78
79 ```javascript
80 $(document).ready(function(){
81    $("#date").inputmask("d/m/y",{ "oncomplete": function(){ alert('inputmask complete'); } });
82    $("#date").inputmask("d/m/y",{ "onincomplete": function(){ alert('inputmask incomplete'); } });
83    $("#date").inputmask("d/m/y",{ "oncleared": function(){ alert('inputmask cleared'); } });
84 });
85 ```
86
87 ### clearIncomplete - clear the incomplete input on blur
88
89 ```javascript
90 $(document).ready(function(){
91    $("#date").inputmask("d/m/y",{ "clearIncomplete": true } });
92 });
93 ```
94
95 ### mask repeat function
96
97 ```javascript
98 $(document).ready(function(){
99    $("#number").inputmask({ "mask": "9", "repeat": 10 });  // ~ mask "9999999999"
100 });
101 ```
102
103 ### mask non-greedy repeat function
104
105 ```javascript
106 $(document).ready(function(){
107    $("#number").inputmask({ "mask": "9", "repeat": 10, "greedy": false });  // ~ mask "9" or mask "99" or ... mask "9999999999"
108 });
109 ```
110
111 ### get the unmaskedvalue
112
113 ```javascript
114 $(document).ready(function(){
115    $("#number").inputmask('unmaskedvalue');
116 });
117 ```
118
119 ### set a value and apply mask
120
121 this can be done with the traditionnal jquery.val function (all browsers) or javascript value property for browsers which implement lookupGetter or getOwnPropertyDescriptor
122
123 ```javascript
124 $(document).ready(function(){
125    $("#number").val(12345);
126
127    var number = document.getElementById("number");
128    number.value = 12345;
129 });
130 ```
131
132 with the autoUnmaskoption you can change the return of $.fn.val (or value property)  to unmaskedvalue or the maskedvalue
133
134 ```javascript
135 $(document).ready(function(){
136        $('#<%= tbDate.ClientID%>').inputmask({ "mask": "d/m/y", 'autoUnmask' : true});    //  value: 23/03/1973
137     alert($('#<%= tbDate.ClientID%>').val());    // shows 23031973     (autoUnmask: true)
138
139     var tbDate = document.getElementById("<%= tbDate.ClientID%>");
140     alert(tbDate.value);    // shows 23031973     (autoUnmask: true)
141 });
142 ```
143
144 ### add custom definitions
145
146 You can define your own definitions to use in your mask.  
147 Start by choosing a masksymbol. 
148
149 ##### validator
150 Next define your validator.  The validator can be a regular expression or a function.
151
152 ##### cardinality
153 Cardinality specifies how many characters are represented and validated for the definition.
154
155 ##### prevalidator
156  The prevalidator option is 
157 used to validate the characters before the definition cardinality is reached. (see 'j' example)
158
159 ##### definitionSymbol
160 When you insert or delete characters, they are only shifted when the definition type is the same.  This behavior can be overridden
161 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)
162
163 ```javascript
164 $.extend($.inputmask.defaults.definitions, {
165     'f': {  //masksymbol
166         "validator": "[0-9\(\)\.\+/ ]",
167         "cardinality": 1,
168         'prevalidator': null
169     },
170     'g': {
171         "validator": function (chrs, buffer, pos, strict, opts) { 
172             //do some logic and return true, false, or { "pos": new position, "c": character to place }
173         }        
174         "cardinality": 1,
175         'prevalidator': null
176     },
177     'j': { //basic year
178             validator: "(19|20)\\d{2}",
179             cardinality: 4,
180             prevalidator: [
181                         { validator: "[12]", cardinality: 1 },
182                         { validator: "(19|20)", cardinality: 2 },
183                         { validator: "(19|20)\\d", cardinality: 3 }
184             ]
185      }, 
186      'x': {
187         validator: "[0-2]",
188         cardinality: 1,
189         definitionSymbol: "i" //this allows shifting values from other definitions, with the same masksymbol or definitionSymbol
190      },
191      'y': {
192         validator: function (chrs, buffer, pos, strict, opts) {
193                         var valExp2 = new RegExp("2[0-5]|[01][0-9]");
194                         return valExp2.test(buffer[pos - 1] + chrs);
195                     },
196         cardinality: 1,
197         definitionSymbol: "i"
198      },
199      'z': {
200         validator: function (chrs, buffer, pos, strict, opts) {
201                        var valExp3 = new RegExp("25[0-5]|2[0-4][0-9]|[01][0-9][0-9]");
202                         return valExp3.test(buffer[pos - 2] + buffer[pos - 1] + chrs);
203         },
204         cardinality: 1,
205         definitionSymbol: "i"
206       }
207 });
208 ```
209
210 ### set defaults
211
212 ```javascript
213 $.extend($.inputmask.defaults, {
214     'autounmask': true
215 });
216 ```
217
218 ### numeric input direction
219
220 ```javascript
221 $(document).ready(function(){
222     $(selector).inputmask('€ 999.999.999,99', { numericInput: true });    //123456  =>  € ___.__1.234,56
223 });
224 ```
225
226 If you define a radixPoint the caret will always jump to the integer part, until you type the radixpoint.  
227
228 ```javascript
229 $(document).ready(function(){
230     $(selector).inputmask('€ 999.999.999,99', { numericInput: true, radixPoint: "," });
231 });
232 ```
233
234 #### align the numerics to the right
235
236 By setting the rightAlignNumerics you can specify to right align a numeric inputmask.  Default is true.  
237
238 ```javascript
239 $(document).ready(function(){
240     $(selector).inputmask('decimal', { rightAlignNumerics: false });  //disables the right alignment of the decimal input
241 });
242 ```
243
244
245 ### remove the inputmask
246
247 ```javascript
248 $(document).ready(function(){
249     $('selector').inputmask('remove');
250 });
251 ```
252
253 ### escape special mask chars
254
255 ```javascript
256 $(document).ready(function(){
257     $("#months").inputmask("m \\months");
258 });
259 ```
260
261 ### clearMaskOnLostFocus
262
263 remove the empty mask on blur or when not empty removes the optional trailing part
264
265 ```javascript
266 $(document).ready(function(){
267     $("#ssn").inputmask("999-99-9999",{placeholder:" ", clearMaskOnLostFocus: true }); //default
268 });
269 ```
270
271 ### Optional Masks
272
273 It is possible to define some parts in the mask as optional.  This is done by using [ ].
274
275 Example:
276
277 ```javascript
278 $('#test').inputmask('(99) 9999[9]-9999');
279 ```
280 This mask wil allow input like (99) 99999-9999 or (99) 9999-9999.  
281 Input => 12123451234      mask => (12) 12345-1234    (trigger complete)  
282 Input => 121234-1234      mask => (12) 1234-1234     (trigger complete)  
283 Input => 1212341234       mask => (12) 12341-234_    (trigger incomplete)  
284
285 #### skipOptionalPartCharacter
286 As an extra there is another configurable character which is used to skip an optional part in the mask.  
287
288 ```javascript
289 skipOptionalPartCharacter: " ",
290 ```
291 Input => 121234 1234      mask => (12) 1234-1234     (trigger complete)  
292
293 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.
294
295 For example, given:
296
297 ```javascript
298 $('#test').inputmask('999[-AAA]');
299 ```
300 While the field has focus and is blank, users will see the full mask `___-___`.
301 When the required part of the mask is filled and the field loses focus, the user will see `123`.
302 When both the required and optional parts of the mask are filled out and the field loses focus, the user will see `123-ABC`.
303
304 ### Multiple masks
305
306 You can define multiple mask for your input.  Depending on the input the masking will switch between the defined masks.  
307 This can be usefull when the masks are too different to solve it with optional parts.
308
309 ```javascript
310   $(selector).inputmask({ mask: ["999.999", "aa-aa-aa"]});
311 ```
312
313 ### aliases option
314
315 First you have to create an alias definition (more examples can be found in jquery.inputmask.extensions.js)
316
317 ```javascript
318 $.extend($.inputmask.defaults.aliases, {
319         'date': {
320             mask: "d/m/y"
321         },
322         'dd/mm/yyyy': {
323         alias: "date"
324     }
325 });
326 ```
327
328 use:
329
330 ```javascript
331 $(document).ready(function(){
332    $("#date").inputmask("date");    //   => equals to    $("#date").inputmask("d/m/y");
333 });
334 ```
335
336 or use the dd/mm/yyyy alias of the date alias:
337
338 ```javascript
339 $(document).ready(function(){
340    $("#date").inputmask("dd/mm/yyyy");   //    => equals to    $("#date").inputmask("d/m/y");
341 });
342 ```
343
344 ### auto upper/lower- casing inputmask
345
346 see jquery.inputmask.extensions.js for an example how to define "auto"-casing in a definition (definition A)
347 casing can be null, "upper" or "lower"
348
349 ```javascript
350 $(document).ready(function(){
351    $("#test").inputmask("999-AAA");    //   => 123abc ===> 123-ABC
352 });
353 ```
354 ### getemptymask command
355
356 return the default (empty) mask value
357
358
359 ```javascript
360 $(document).ready(function(){
361    $("#test").inputmask("999-AAA");
362    var initialValue = $("#test").inputmask("getemptymask");  // initialValue  => "___-___"
363 });
364 ```
365
366 ### onKeyUp / onKeyDown option
367
368 Use this to do some extra processing of the input when certain keys are pressed.
369 This can be usefull when implementing an alias, ex. decimal alias, autofill the digits when pressing tab.
370
371 see jquery.inputmask.extensions.js for some examples
372
373 ### hasMaskedValue
374
375 Check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value 
376
377 ```javascript
378 $(document).ready(function(){
379     function validateMaskedValue(val){}
380     function validateValue(val){}
381
382     var val = $("#test").val();
383     if($("#test").inputmask("hasMaskedValue"))
384       validateMaskedValue(val); 
385    else validateValue(val); 
386 });
387 ```
388 ### showMaskOnFocus
389
390 Shows the mask when the input gets focus. (default = true)
391
392 ```javascript
393 $(document).ready(function(){
394     $("#ssn").inputmask("999-99-9999",{ showMaskOnFocus: true }); //default
395 });
396 ```
397
398 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.
399
400 ### showMaskOnHover
401
402 Shows the mask when hovering the mouse. (default = true)
403
404 ```javascript
405 $(document).ready(function(){
406     $("#ssn").inputmask("999-99-9999",{ showMaskOnHover: true }); //default
407 });
408 ```
409 ### onKeyValidation
410
411 Callback function is executed on every keyvalidation with the result as parameter.
412
413 ```javascript
414 $(document).ready(function(){
415     $("#ssn").inputmask("999-99-9999",
416             { onKeyValidation: function (result) {
417                                 console.log(result);
418                                 } });
419 });
420 ```
421 ### isComplete
422
423 Verify wheter the current value is complete or not.
424
425 ```javascript
426 $(document).ready(function(){
427     if($("#ssn").inputmask("isComplete")){
428         //do something
429     }
430 });
431 ```
432
433 ## Supported markup options
434 ### RTL attribute
435
436 ```html
437 <input id="test" dir="rtl" />
438 ```
439 ### readonly attribute
440
441 ```html
442 <input id="test" readonly="readonly" />
443 ```
444 ### disabled attribute
445
446 ```html
447 <input id="test" disabled="disabled" />
448 ```
449
450 ### maxlength attribute
451
452 ```html
453 <input id="test" maxlength="4" />
454 ```
455 ### data-inputmask attribute
456
457 You can also apply an inputmask by using the data-inputmask attribute.  In the attribute you specify the options wanted for the inputmask.
458 This gets parsed with $.parseJSON (for the moment), so be sure to use a welformed json-string without the {}.
459
460 ```html
461 <input data-inputmask="'alias': 'date'" />
462 <input data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false" />
463 ```
464 ```javascript
465 $(document).ready(function(){
466     $(":input").inputmask();
467 });
468 ```
469
470 ## Compiling with Google Closure Compiler
471
472 First grab the sources from github.  In the root you type ant.
473 A new folder dist is created with the minified and optimized js-files
474
475 ## .NET Nuget Package Install
476 ```html
477 PM> Install-Package jQuery.InputMask
478 ```
479
480 In App_Start, BundleConfig.cs
481 ```c#
482 bundles.Add(new ScriptBundle("~/bundles/inputmask").Include(
483                         "~/Scripts/jquery.inputmask/jquery.inputmask.js",
484                         "~/Scripts/jquery.inputmask/jquery.inputmask.extensions.js",
485                         "~/Scripts/jquery.inputmask/jquery.inputmask.date.extensions.js",
486                         "~/Scripts/jquery.inputmask/jquery.inputmask.numeric.extensions.js"));
487 ```
488
489 In Layout
490 ```html
491 @Scripts.Render("~/bundles/inputmask")
492 ```
493
494
495 # jquery.inputmask extensions
496
497 ## Alias definitions
498
499 ### date & datetime aliases
500
501 ```javascript
502 $(document).ready(function(){
503    $("#date").inputmask("dd/mm/yyyy");
504    $("#date").inputmask("mm/dd/yyyy");
505    $("#date").inputmask("date"); // alias for dd/mm/yyyy
506    $("#date").inputmask("date", {yearrange: { minyear: 1900, maxyear: 2099 }}); //specify year range
507 });
508 ```
509
510 The date aliases take leapyears into account.  There is also autocompletion on day, month, year.
511 For example:
512
513 input:    2/2/2012         result: 02/02/2012  
514 input:  352012            result: 03/05/2012  
515 input:  3/530            result: 03/05/2030  
516 input:  ctrl rightarrow            result: the date from today  
517
518 ```javascript
519 $(document).ready(function(){
520    $("#date").inputmask("datetime"); // 24h
521    $("#date").inputmask("datetime12"); // am/pm
522 });
523 ```
524
525 ### numeric aliases
526
527 ```javascript
528 $(document).ready(function(){
529    $("#numeric").inputmask("decimal");
530    $("#numeric").inputmask("non-negative-decimal");
531    $("#numeric").inputmask("integer");
532 });
533 ```
534
535 With the decimal mask the caret will always jump to the integer part, until you type the radixpoint.  
536 There is autocompletion on tab with decimal numbers.
537
538 Define the radixpoint
539
540 ```javascript
541 $(document).ready(function(){
542    $("#numeric").inputmask("decimal", { radixPoint: "," });
543 });
544 ```
545 Define the number of digits after the radixpoint
546
547 ```javascript
548 $(document).ready(function(){
549    $("#numeric").inputmask("decimal", { digits: 3 });
550 });
551 ```
552 Grouping support through:  autoGroup, groupSeparator, groupSize
553 ```javascript
554 $(document).ready(function(){
555    $("#numeric").inputmask("decimal", { radixPoint: ",", autoGroup: true, groupSeparator: ".", groupSize: 3 });
556 });
557 ```
558
559 ### other aliases
560
561 An ip adress alias for entering valid ip-addresses.
562
563 ```javascript
564 $(document).ready(function(){
565    $(selector).inputmask("ip");
566 });
567 ```
568
569 You can find/modify/extend this alias in the jquery.inputmask.extensions.js
570
571