UNPKG

33.2 kBMarkdownView Raw
1# Inputmask 3.x
2
3Copyright (c) 2010 - 2016 Robin Herbots Licensed under the MIT license ([http://opensource.org/licenses/mit-license.php](http://opensource.org/licenses/mit-license.php))
4
5[![NPM Version][npm-image]][npm-url] [![Dependency Status][david-image]][david-url] [![devDependency Status][david-dev-image]][david-dev-url]
6
7Inputmask is a javascript library which creates an input mask. Inputmask can run against vanilla javascript, jQuery and jqlite.
8
9An inputmask helps the user with the input by ensuring a predefined format. This can be useful for dates, numerics, phone numbers, ...
10
11Highlights:
12- easy to use
13- optional parts anywere in the mask
14- possibility to define aliases which hide complexity
15- date / datetime masks
16- numeric masks
17- lots of callbacks
18- non-greedy masks
19- many features can be enabled/disabled/configured by options
20- supports readonly/disabled/dir="rtl" attributes
21- support data-inputmask attribute(s)
22- alternator-mask
23- regex-mask
24- dynamic-mask
25- preprocessing-mask
26- JIT-masking
27- value formatting / validating without input element
28- AMD/CommonJS support
29- dependencyLibs: vanilla javascript, jQuery, jqlite
30- [Android support](README_android.md)
31
32Demo page see [http://robinherbots.github.io/Inputmask](http://robinherbots.github.io/Inputmask)
33
34[![donate](https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=ZNR3EB6JTMMSS)
35
36## Usage:
37Include the js-files which you can find in the `dist` folder.
38
39via Inputmask class
40
41```html
42<script src="jquery.js"></script>
43<script src="inputmask.js"></script>
44<script src="inputmask.???.Extensions.js"></script>
45```
46
47```javascript
48var selector = document.getElementById("selector");
49
50var im = new Inputmask("99-9999999");
51im.mask(selector);
52
53Inputmask({"mask": "(999) 999-9999", .... other options .....}).mask(selector);
54Inputmask("9-a{1,3}9{1,3}").mask(selector);
55Inputmask("9", { repeat: 10 }).mask(selector);
56```
57
58via jquery plugin
59
60```html
61<script src="jquery.js"></script>
62<script src="inputmask.js"></script>
63<script src="inputmask.???.Extensions.js"></script>
64<script src="jquery.inputmask.js"></script>
65```
66
67or with the bundled version
68
69```html
70<script src="jquery.js"></script>
71<script src="jquery.inputmask.bundle.js"></script>
72```
73
74```javascript
75$(document).ready(function(){
76 $(selector).inputmask("99-9999999"); //static mask
77 $(selector).inputmask({"mask": "(999) 999-9999"}); //specifying options
78 $(selector).inputmask("9-a{1,3}9{1,3}"); //mask with dynamic syntax
79});
80```
81
82via data-inputmask attribute
83
84```html
85<input data-inputmask="'alias': 'date'" />
86<input data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false" />
87<input data-inputmask="'mask': '99-9999999'" />
88```
89
90```javascript
91$(document).ready(function(){
92 $(":input").inputmask();
93 or
94 Inputmask().mask(document.querySelectorAll("input"));
95});
96```
97
98Any option can also be passed through the use of a data attribute. Use data-inputmask-<**_the name of the option_**>="value"
99
100```html
101<input id="example1" data-inputmask-clearmaskonlostfocus="false" />
102<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])?" />
103```
104
105```javascript
106$(document).ready(function(){
107 $("#example1").inputmask("99-9999999");
108 $("#example2").inputmask("Regex");
109});
110```
111
112If 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
113
114```html
115...
116<script src="inputmask.binding.js"></script>
117...
118```
119
120If you use a module loader like requireJS
121
122Have a look at the inputmask.loader.js for usage.
123
124Example config.js
125
126```javascript
127paths: {
128 ...
129 "inputmask.dependencyLib": "../dist/inputmask/inputmask.dependencyLib",
130 "inputmask": "../dist/inputmask/inputmask",
131 ...
132}
133```
134
135As dependencyLib you can choose between the supported libraries.
136- inputmask.dependencyLib (vanilla)
137- inputmask.dependencyLib.jquery
138- inputmask.dependencyLib.jqlite
139- .... (others are welcome)
140
141### Allowed HTML-elements
142- `<input type="text">`
143- `<input type="tel">`
144- `<input type="password">`
145- `<div contenteditable="true">` (and all others supported by contenteditable)
146- `<textarea>`
147- any html-element (mask text content or set maskedvalue with jQuery.val)
148
149The allowed input types are defined in the supportsInputType option. Also see ([input-type-ref])
150
151### Default masking definitions
152- `9` : numeric
153- `a` : alphabetical
154- `*` : alphanumeric
155
156There are more definitions defined within the extensions.<br>You can find info within the js-files or by further exploring the options.
157
158## Masking types
159### Static masks
160These are the very basic of masking. The mask is defined and will not change during the input.
161
162```javascript
163$(document).ready(function(){
164 $(selector).inputmask("aa-9999"); //static mask
165 $(selector).inputmask({mask: "aa-9999"}); //static mask
166});
167```
168
169### Optional masks
170It is possible to define some parts in the mask as optional. This is done by using [ ].
171
172Example:
173
174```javascript
175$('#test').inputmask('(99) 9999[9]-9999');
176```
177
178This mask wil allow input like `(99) 99999-9999` or `(99) 9999-9999`.
179
180Input => 12123451234 mask => (12) 12345-1234 (trigger complete)<br>
181Input => 121234-1234 mask => (12) 1234-1234 (trigger complete)<br>
182Input => 1212341234 mask => (12) 12341-234_ (trigger incomplete)
183
184#### skipOptionalPartCharacter
185As an extra there is another configurable character which is used to skip an optional part in the mask.
186
187```javascript
188skipOptionalPartCharacter: " "
189```
190
191Input => 121234 1234 mask => (12) 1234-1234 (trigger complete)
192
193When `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.
194
195For example, given:
196
197```javascript
198$('#test').inputmask('999[-AAA]');
199```
200
201While 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`.
202
203#### Optional masks with greedy false
204When defining an optional mask together with the greedy: false option, the inputmask will show the smallest possible mask as input first.
205
206```javascript
207$(selector).inputmask({ mask: "9[-9999]", greedy: false });
208```
209
210The initial mask shown will be "**_**" instead of "**_**-____".
211
212### Dynamic masks
213Dynamic masks can change during the input. To define a dynamic part use { }.
214
215{n} => n repeats<br>{n,m} => from n to m repeats
216
217Also {+} and {*} is allowed. + start from 1 and * start from 0.
218
219```javascript
220$(document).ready(function(){
221 $(selector).inputmask("aa-9{4}"); //static mask with dynamic syntax
222 $(selector).inputmask("aa-9{1,4}"); //dynamic mask ~ the 9 def can be occur 1 to 4 times
223
224 //email mask
225 $(selector).inputmask({
226 mask: "*{1,20}[.*{1,20}][.*{1,20}][.*{1,20}]@*{1,20}[.*{2,6}][.*{1,2}]",
227 greedy: false,
228 onBeforePaste: function (pastedValue, opts) {
229 pastedValue = pastedValue.toLowerCase();
230 return pastedValue.replace("mailto:", "");
231 },
232 definitions: {
233 '*': {
234 validator: "[0-9A-Za-z!#$%&'*+/=?^_`{|}~\-]",
235 cardinality: 1,
236 casing: "lower"
237 }
238 }
239 });
240});
241```
242
243### Alternator masks
244The alternator syntax is like an **OR** statement. The mask can be one of the 2 choices specified in the alternator.
245
246To define an alternator use the |.<br>ex: "a|9" => a or 9<br> "(aaa)|(999)" => aaa or 999
247
248Also make sure to read about the keepStatic option.
249
250```javascript
251$("selector").inputmask("(99.9)|(X)", {
252 definitions: {
253 "X": {
254 validator: "[xX]",
255 cardinality: 1,
256 casing: "upper"
257 }
258 }
259});
260```
261
262or
263
264```javascript
265$("selector").inputmask({
266 mask: ["99.9", "X"],
267 definitions: {
268 "X": {
269 validator: "[xX]",
270 cardinality: 1,
271 casing: "upper"
272 }
273 }
274});
275```
276
277### Preprocessing masks
278You 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.
279
280```javascript
281$(selector).inputmask({ mask: function () { /* do stuff */ return ["[1-]AAA-999", "[1-]999-AAA"]; }});
282```
283
284### JIT Masking
285Just in time masking. With the jitMasking option you can enable jit masking. The mask will only be visible for the user entered characters.
286Default: false
287
288Value can be true or a threshold number or false.
289
290```javascript
291Inputmask("date", { jitMasking: true }).mask(selector);
292```
293
294## Define custom definitions
295You can define your own definitions to use in your mask.<br>Start by choosing a masksymbol.
296
297### validator(chrs, maskset, pos, strict, opts)
298Next define your validator. The validator can be a regular expression or a function.
299
300The return value of a validator can be true, false or a command object.
301
302#### Options of the command object
303- pos : position to insert
304- c : character to insert
305- caret : position of the caret
306- remove : position(s) to remove
307 - pos or [pos1, pos2]
308
309- insert : position(s) to add :
310 - { pos : position to insert, c : character to insert }
311 - [{ pos : position to insert, c : character to insert }, { ...}, ... ]
312
313- refreshFromBuffer :
314 - true => refresh validPositions from the complete buffer
315 - { start: , end: } => refresh from start to end
316
317### cardinality
318Cardinality specifies how many characters are represented and validated for the definition.
319
320### prevalidator(chrs, maskset, pos, strict, opts)
321The prevalidator option is used to validate the characters before the definition cardinality is reached. (see 'j' example)
322
323### definitionSymbol
324When 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)
325
326```javascript
327Inputmask.extendDefinitions({
328 'f': { //masksymbol
329 "validator": "[0-9\(\)\.\+/ ]",
330 "cardinality": 1,
331 'prevalidator': null
332 },
333 'g': {
334 "validator": function (chrs, buffer, pos, strict, opts) {
335 //do some logic and return true, false, or { "pos": new position, "c": character to place }
336 }
337 "cardinality": 1,
338 'prevalidator': null
339 },
340 'j': { //basic year
341 validator: "(19|20)\\d{2}",
342 cardinality: 4,
343 prevalidator: [
344 { validator: "[12]", cardinality: 1 },
345 { validator: "(19|20)", cardinality: 2 },
346 { validator: "(19|20)\\d", cardinality: 3 }
347 ]
348 },
349 'x': {
350 validator: "[0-2]",
351 cardinality: 1,
352 definitionSymbol: "i" //this allows shifting values from other definitions, with the same masksymbol or definitionSymbol
353 },
354 'y': {
355 validator: function (chrs, buffer, pos, strict, opts) {
356 var valExp2 = new RegExp("2[0-5]|[01][0-9]");
357 return valExp2.test(buffer[pos - 1] + chrs);
358 },
359 cardinality: 1,
360 definitionSymbol: "i"
361 },
362 'z': {
363 validator: function (chrs, buffer, pos, strict, opts) {
364 var valExp3 = new RegExp("25[0-5]|2[0-4][0-9]|[01][0-9][0-9]");
365 return valExp3.test(buffer[pos - 2] + buffer[pos - 1] + chrs);
366 },
367 cardinality: 1,
368 definitionSymbol: "i"
369 }
370});
371```
372
373### placeholder
374Specify a placeholder for a definition.
375
376### set defaults
377Defaults can be set as below.
378
379```javascript
380Inputmask.extendDefaults({
381 'autoUnmask': true
382});
383Inputmask.extendDefinitions({
384 'A': {
385 validator: "[A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]",
386 cardinality: 1,
387 casing: "upper" //auto uppercasing
388 },
389 '+': {
390 validator: "[0-9A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]",
391 cardinality: 1,
392 casing: "upper"
393 }
394});
395Inputmask.extendAliases({
396 'Regex': {
397 mask: "r",
398 greedy: false,
399 ...
400 }
401});
402```
403
404But if the property is defined within an alias you need to set it for the alias definition.
405
406```javascript
407Inputmask.extendAliases({
408 'numeric': {
409 allowPlus: false,
410 allowMinus: false
411 }
412});
413```
414
415However, the preferred way to alter properties for an alias is by creating a new alias which inherits from the default alias definition.
416
417```javascript
418Inputmask.extendAliases({
419 'myNum': {
420 alias: "numeric",
421 placeholder: '',
422 allowPlus: false,
423 allowMinus: false
424 }
425});
426```
427
428Once defined, you can call the alias by:
429
430```javascript
431$(selector).inputmask("myNum");
432```
433
434All callbacks are implemented as options. This means that you can set general implementations for the callbacks by setting a default.
435
436```javascript
437Inputmask.extendDefaults({
438 onKeyValidation: function(key, result){
439 if (!result){
440 alert('Your input is not valid')
441 }
442 }
443});
444```
445
446## Methods:
447### mask(elems)
448Create a mask for the input.
449
450```javascript
451$(selector).inputmask({ mask: "99-999-99"});
452```
453
454or
455
456```javascript
457Inputmask({ mask: "99-999-99"}).mask(document.querySelectorAll(selector));
458```
459
460or
461
462```javascript
463Inputmask("99-999-99").mask(document.querySelectorAll(selector));
464```
465
466or
467
468```javascript
469var im = new Inputmask("99-999-99");
470im.mask(document.querySelectorAll(selector));
471```
472
473or
474
475```javascript
476Inputmask("99-999-99").mask(selector);
477```
478
479### unmaskedvalue
480Get the `unmaskedvalue`
481
482
483```javascript
484$(selector).inputmask('unmaskedvalue');
485```
486
487or
488
489```javascript
490var input = document.getElementById(selector);
491if (input.inputmask)
492 input.inputmask.unmaskedvalue()
493```
494
495#### Value unmasking
496Unmask a given value against the mask.
497
498```javascript
499var unformattedDate = Inputmask.unmask("23/03/1973", { alias: "dd/mm/yyyy"}); //23031973
500```
501
502### remove
503Remove the `inputmask`.
504
505```javascript
506$(selector).inputmask('remove');
507```
508
509or
510
511```javascript
512var input = document.getElementById(selector);
513if (input.inputmask)
514 input.inputmask.remove()
515```
516
517or
518
519```javascript
520Inputmask.remove(document.getElementById(selector));
521```
522
523### getemptymask
524return the default (empty) mask value
525
526```javascript
527$(document).ready(function(){
528 $("#test").inputmask("999-AAA");
529 var initialValue = $("#test").inputmask("getemptymask"); // initialValue => "___-___"
530});
531```
532
533### hasMaskedValue
534Check whether the returned value is masked or not; currently only works reliably when using jquery.val fn to retrieve the value
535
536```javascript
537$(document).ready(function(){
538 function validateMaskedValue(val){}
539 function validateValue(val){}
540
541 var val = $("#test").val();
542 if ($("#test").inputmask("hasMaskedValue"))
543 validateMaskedValue(val);
544 else
545 validateValue(val);
546});
547```
548
549### isComplete
550Verify whether the current value is complete or not.
551
552```javascript
553$(document).ready(function(){
554 if ($(selector).inputmask("isComplete")){
555 //do something
556 }
557});
558```
559
560### getmetadata
561The 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.
562
563```javascript
564$(selector).inputmask("getmetadata");
565```
566
567### setvalue
568The 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.
569
570### option(options, noremask)
571Get or set an option on an existing inputmask.
572The option method is intented for adding extra options like callbacks, etc at a later time to the mask.
573
574When extra options are set the mask is automatically reapplied, unless you pas true for the noremask argument.
575
576Set an option
577```javascript
578document.querySelector("#CellPhone").inputmask.option({
579 onBeforePaste: function (pastedValue, opts) {
580 return phoneNumOnPaste(pastedValue, opts);
581 }
582});
583```
584
585```javascript
586$("#CellPhone").inputmask("option", {
587 onBeforePaste: function (pastedValue, opts) {
588 return phoneNumOnPaste(pastedValue, opts);
589 }
590})
591```
592
593### format
594Instead 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.
595
596```javascript
597var formattedDate = Inputmask.format("2331973", { alias: "dd/mm/yyyy"});
598```
599
600### isValid
601Validate a given value against the mask.
602
603```javascript
604var isValid = Inputmask.isValid("23/03/1973", { alias: "dd/mm/yyyy"});
605```
606
607## Options:
608### placeholder
609Change the mask placeholder.
610Default: "_"
611
612Instead of "_", you can change the unfilled characters mask as you like, simply by adding the `placeholder` option.<br>
613For example, `placeholder: " "` will change the default autofill with empty values
614
615```javascript
616$(document).ready(function(){
617 $("#date").inputmask("99/99/9999",{ "placeholder": "*" });
618});
619```
620
621or a multi-char placeholder
622
623```javascript
624$(document).ready(function(){
625 $("#date").inputmask("99/99/9999",{ "placeholder": "dd/mm/yyyy" });
626});
627```
628
629### optionalmarker
630Definition of the symbols used to indicate an optional part in the mask.
631
632```javascript
633optionalmarker: { start: "[", end: "]" }
634```
635
636### quantifiermarker
637Definition of the symbols used to indicate a quantifier in the mask.
638
639```javascript
640quantifiermarker: { start: "{", end: "}" }
641```
642
643### groupmarker
644Definition of the symbols used to indicate a group in the mask.
645
646```javascript
647groupmarker: { start: "(", end: ")" }
648```
649
650### alternatormarker
651Definition of the symbols used to indicate an alternator part in the mask.
652
653```javascript
654alternatormarker: "|"
655```
656
657### escapeChar
658Definition of the symbols used to escape a part in the mask.
659
660```javascript
661escapeChar: "\\"
662```
663
664See **escape special mask chars**
665
666### mask
667The mask to use.
668
669### oncomplete
670Execute a function when the mask is completed
671
672```javascript
673$(document).ready(function(){
674 $("#date").inputmask("99/99/9999",{ "oncomplete": function(){ alert('inputmask complete'); } });
675});
676```
677
678### onincomplete
679Execute a function when the mask is incomplete. Executes on blur.
680
681```javascript
682$(document).ready(function(){
683 $("#date").inputmask("99/99/9999",{ "onincomplete": function(){ alert('inputmask incomplete'); } });
684});
685```
686
687### oncleared
688Execute a function when the mask is cleared.
689
690```javascript
691$(document).ready(function(){
692 $("#date").inputmask("99/99/9999",{ "oncleared": function(){ alert('inputmask cleared'); } });
693});
694```
695
696### repeat
697Mask repeat function. Repeat the mask definition x-times.
698
699```javascript
700$(document).ready(function(){
701 $("#number").inputmask({ "mask": "9", "repeat": 10 }); // ~ mask "9999999999"
702});
703```
704
705### greedy
706Toggle to allocate as much possible or the opposite. Non-greedy repeat function.
707
708```javascript
709$(document).ready(function(){
710 $("#number").inputmask({ "mask": "9", "repeat": 10, "greedy": false }); // ~ mask "9" or mask "99" or ... mask "9999999999"
711});
712```
713
714With the non-greedy option set to false, you can specify * as repeat. This makes an endless repeat.
715
716### autoUnmask
717Automatically unmask the value when retrieved.<br>Default: false.
718
719**When setting this option to true the plugin also expects the initial value from the server to be unmasked.**
720
721### removeMaskOnSubmit
722Remove the mask before submitting the form.<br>Default: false
723
724### clearMaskOnLostFocus
725Remove the empty mask on blur or when not empty removes the optional trailing part Default: true
726
727```javascript
728$(document).ready(function(){
729 $("#ssn").inputmask("999-99-9999",{placeholder:" ", clearMaskOnLostFocus: true }); //default
730});
731```
732
733### insertMode
734Toggle to insert or overwrite input.<br>Default: true.<br>This option can be altered by pressing the Insert key.
735
736### clearIncomplete
737Clear the incomplete input on blur
738
739```javascript
740$(document).ready(function(){
741 $("#date").inputmask("99/99/9999",{ "clearIncomplete": true });
742});
743```
744
745### aliases
746Definitions of aliases.
747
748With 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.
749
750First you have to create an alias definition. The alias definition can contain options for the mask, custom definitions, the mask to use etc.
751
752When 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.
753
754Some examples can be found in jquery.inputmask.xxx.extensions.js
755
756use:
757
758```javascript
759$("#date").inputmask("date");
760```
761
762or
763
764```javascript
765$("#date").inputmask({ alias: "date"});
766```
767
768You can also call an alias and extend it with some more options
769
770```javascript
771$("#date").inputmask("date", { "clearIncomplete": true });
772```
773
774or
775
776```javascript
777$("#date").inputmask({ alias: "date", "clearIncomplete": true });
778```
779
780### alias
781The alias to use.
782
783```javascript
784$("#date").inputmask({ alias: "email"});
785```
786
787### onKeyDown
788Callback to implement autocomplete on certain keys for example
789
790Function arguments: event, buffer, caretPos, opts<br>Function return:
791
792### onBeforeMask
793Executes before masking the initial value to allow preprocessing of the initial value.
794
795Function arguments: initialValue, opts<br>Function return: processedValue
796
797```javascript
798$(selector).inputmask({
799 alias: 'phonebe',
800 onBeforeMask: function (value, opts) {
801 var processedValue = value.replace(/^0/g, "");
802 if (processedValue.indexOf("32") > 1 || processedValue.indexOf("32") == -1) {
803 processedValue = "32" + processedValue;
804 }
805
806 return processedValue;
807 }
808});
809```
810
811### onBeforePaste
812This 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.
813
814Function arguments: pastedValue, opts<br>Function return: processedValue
815
816```javascript
817$(selector).inputmask({
818 mask: '9999 9999 9999 9999',
819 placeholder: ' ',
820 showMaskOnHover: false,
821 showMaskOnFocus: false,
822 onBeforePaste: function (pastedValue, opts) {
823 var processedValue = pastedValue;
824
825 //do something with it
826
827 return processedValue;
828 }
829});
830```
831
832You can also disable pasting a value by returning false in the onBeforePaste call.
833
834Default: Calls the onBeforeMask
835
836### onBeforeWrite
837Executes before writing to the masked element
838
839Use 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.
840
841Function arguments: event, buffer, caretPos, opts<br>Function return: command object (see Define custom definitions)
842
843### onUnMask
844Executes after unmasking to allow post-processing of the unmaskedvalue.
845
846Function arguments: maskedValue, unmaskedValue<br>Function return: processedValue
847
848```javascript
849$(document).ready(function(){
850 $("#number").inputmask("decimal", { onUnMask: function(maskedValue, unmaskedValue) {
851 //do something with the value
852 return unmaskedValue;
853 }});
854});
855```
856
857### showMaskOnFocus
858Shows the mask when the input gets focus. (default = true)
859
860```javascript
861$(document).ready(function(){
862 $("#ssn").inputmask("999-99-9999",{ showMaskOnFocus: true }); //default
863});
864```
865
866To 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.
867
868### showMaskOnHover
869Shows the mask when hovering the mouse. (default = true)
870
871```javascript
872$(document).ready(function(){
873 $("#ssn").inputmask("999-99-9999",{ showMaskOnHover: true }); //default
874});
875```
876
877### onKeyValidation
878Callback function is executed on every keyvalidation with the key & result as parameter.
879
880```javascript
881$(document).ready(function(){
882 $("#ssn").inputmask("999-99-9999", {
883 onKeyValidation: function (key, result) {
884 console.log(key + " - " + result);
885 }
886 });
887});
888```
889
890### skipOptionalPartCharacter
891
892### numericInput
893Numeric input direction. Keeps the caret at the end.
894
895```javascript
896$(document).ready(function(){
897 $(selector).inputmask('€ 999.999.999,99', { numericInput: true }); //123456 => € ___.__1.234,56
898});
899```
900
901### rightAlign
902Align the input to the right
903
904By 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.
905
906```javascript
907$(document).ready(function(){
908 $(selector).inputmask('decimal', { rightAlign: false }); //disables the right alignment of the decimal input
909});
910```
911
912### undoOnEscape
913Make escape behave like undo. (ctrl-Z)<br>Pressing escape reverts the value to the value before focus.<br>Default: true
914
915### radixPoint (numerics)
916Define the radixpoint (decimal separator)<br>Default: ""
917
918### groupSeparator (numerics)
919Define the groupseparator<br>Default: ""
920
921### keepStatic
922Default: 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.
923
924ex. $(selector).inputmask({ mask: ["+55-99-9999-9999", "+55-99-99999-9999", ], keepStatic: true });
925
926typing 1212345123 => should result in +55-12-1234-5123 type extra 4 => switch to +55-12-12345-1234
927
928When passing multiple masks (an array of masks) keepStatic is automatically set to true unless explicitly set through the options.
929
930### positionCaretOnTab
931When enabled the caret position is set after the latest valid position on TAB Default: true
932
933### tabThrough
934Allows for tabbing through the different parts of the masked field.<br>Default: false
935
936### definitions
937### ignorables
938### isComplete
939With this call-in (hook) you can override the default implementation of the isComplete function.<br>Args => buffer, opts Return => true|false
940
941```javascript
942$(selector).inputmask("Regex", {
943 regex: "[0-9]*",
944 isComplete: function(buffer, opts) {
945 return new RegExp(opts.regex).test(buffer.join(''));
946 }
947});
948```
949
950### canClearPosition
951Hook to alter the clear behavior in the stripValidPositions<br>Args => maskset, position, lastValidPosition, opts<br>Return => true|false
952
953### postValidation
954Hook to postValidate the result from isValid. Usefull for validating the entry as a whole. Args => buffer, currentResult, opts<br>Return => true|false
955
956### staticDefinitionSymbol
957The 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.
958
959In 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".
960
961```javascript
962Inputmask("(99 99 999999)|(i{+})", {
963 definitions: {
964 "i": {
965 validator: ".",
966 cardinality: 1,
967 definitionSymbol: "*"
968 }
969 },
970 staticDefinitionSymbol: "*"
971}).mask(selector);
972```
973
974### nullable
975Return nothing when the user hasn't entered anything.
976Default: true
977
978### positionCaretOnClick
979Positioning of the caret on click. Options none, lvp (based on the last valid position (default), radixFocus (position caret to radixpoint on initial click)
980Default: "lvp"
981
982### casing
983Apply casing at the mask-level.
984Options: null, "upper", "lower" or "title"
985Default: null
986
987### inputmode
988Default: "verbatim"
989Specify the inputmode - already in place for when browsers start to support them
990https://html.spec.whatwg.org/#input-modalities:-the-inputmode-attribute
991
992### colorMask
993Default: false
994Create a css styleable mask.
995Uses css classes: im-caret, im-static.
996
997You need to include the inputmask.css in your page to use this option in full.
998
999## General
1000### set a value and apply mask
1001this can be done with the traditional jquery.val function (all browsers) or JavaScript value property for browsers which implement lookupGetter or getOwnPropertyDescriptor
1002
1003```javascript
1004$(document).ready(function(){
1005 $("#number").val(12345);
1006
1007 var number = document.getElementById("number");
1008 number.value = 12345;
1009});
1010```
1011
1012with the autoUnmaskoption you can change the return of $.fn.val (or value property) to unmaskedvalue or the maskedvalue
1013
1014```javascript
1015$(document).ready(function(){
1016 $('#<%= tbDate.ClientID%>').inputmask({ "mask": "99/99/9999", 'autoUnmask' : true}); // value: 23/03/1973
1017 alert($('#<%= tbDate.ClientID%>').val()); // shows 23031973 (autoUnmask: true)
1018
1019 var tbDate = document.getElementById("<%= tbDate.ClientID%>");
1020 alert(tbDate.value); // shows 23031973 (autoUnmask: true)
1021});
1022```
1023
1024### escape special mask chars
1025
1026```javascript
1027$(document).ready(function(){
1028 $("#months").inputmask("m \\months");
1029});
1030```
1031
1032### auto-casing inputmask
1033You can define within a definition to automatically apply some casing on the entry in an input by giving the casing.<br>Casing can be null, "upper", "lower" or "title".
1034
1035```javascript
1036Inputmask.extendDefinitions({
1037 'A': {
1038 validator: "[A-Za-z]",
1039 cardinality: 1,
1040 casing: "upper" //auto uppercasing
1041 },
1042 '+': {
1043 validator: "[A-Za-z\u0410-\u044F\u0401\u04510-9]",
1044 cardinality: 1,
1045 casing: "upper"
1046 }
1047});
1048```
1049
1050Include jquery.inputmask.extensions.js for using the A and # definitions.
1051
1052```javascript
1053$(document).ready(function(){
1054 $("#test").inputmask("999-AAA"); // => 123abc ===> 123-ABC
1055});
1056```
1057
1058## Supported markup options
1059### RTL attribute
1060
1061```html
1062<input id="test" dir="rtl" />
1063```
1064
1065### readonly attribute
1066
1067```html
1068<input id="test" readonly="readonly" />
1069```
1070
1071### disabled attribute
1072
1073```html
1074<input id="test" disabled="disabled" />
1075```
1076
1077### maxlength attribute
1078
1079```html
1080<input id="test" maxlength="4" />
1081```
1082
1083### data-inputmask attribute
1084You 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 {}.
1085
1086```html
1087<input data-inputmask="'alias': 'date'" />
1088<input data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false" />
1089```
1090
1091```javascript
1092$(document).ready(function(){
1093 $(":input").inputmask();
1094});
1095```
1096
1097### data-inputmask-<option\> attribute
1098All options can also be passed through data-attributes.
1099
1100```html
1101<input data-inputmask-mask="9" data-inputmask-repeat="10" data-inputmask-greedy="false" />
1102```
1103
1104```javascript
1105$(document).ready(function(){
1106 $(":input").inputmask();
1107});
1108```
1109
1110## jQuery.clone
1111When 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)
1112
1113# jquery.inputmask extensions
1114## [date & datetime extensions](README_date.md)
1115## [numeric extensions](README_numeric.md)
1116## [regex extensions](README_regex.md)
1117## [phone extensions](README_phone.md)
1118## [other extensions](README_other.md)
1119
1120[npm-url]: https://npmjs.org/package/jquery.inputmask
1121[npm-image]: https://img.shields.io/npm/v/jquery.inputmask.svg
1122[david-url]: https://david-dm.org/RobinHerbots/jquery.inputmask#info=dependencies
1123[david-image]: https://img.shields.io/david/RobinHerbots/jquery.inputmask.svg
1124[david-dev-url]: https://david-dm.org/RobinHerbots/jquery.inputmask#info=devDependencies
1125[david-dev-image]: https://img.shields.io/david/dev/RobinHerbots/jquery.inputmask.svg
1126[input-type-ref]: https://html.spec.whatwg.org/multipage/forms.html#do-not-apply