Press "Enter" to skip to content

jQuery Creates an Input Mask Plugin | Inputmask

An input mask is a JavaScript library that creates an inputmask. Input mask can work with vanilla javascript, jQuery, and jqlite. An input mask aids the user in input by ensuring a predefined format. This can be useful for dates, numbers, phone numbers and more.

JQuery Input Mask is a lightweight and easy-to-use JavaScript / jQuery plugin that makes it easy to create an input mask. An input mask aids the user in input by ensuring a predefined format. This can be useful for dates, numbers, phone numbers, etc.

jquery input mask example, jquery inputmask example, jquery input mask demo, jquery input mask phone number validation, jquery input mask cdn

Highlights:

  • easy to use
  • optional parts anywhere in the mask
  • possibility to define aliases that hide the complexity
  • date / DateTime masks
  • numeric masks
  • lots of callbacks
  • non-greedy masks
  • many features can be enabled/disabled/configured by options
  • supports read-only/disabled/dir=”RTL” attributes
  • support data-input mask attribute(s)
  • alternator-mask
  • regex-mask
  • dynamic-mask
  • preprocessing-mask
  • JIT-masking
  • value formatting / validating without input element
  • AMD/CommonJS support
  • dependency libs: vanilla javascript, jQuery, jqlite
  • <input-mask> HTML element

How to make use of it:

1. Install and import the Input Mask plugin.

# NPM
$ npm install inputmask --save
// ES6 module
import Inputmask from "inputmask";
<!-- As A Vanilla JS Plugin -->
<script src="/path/to/dist/inputmask.min.js"></script>
<!-- As A jQuery Plugin -->
<script src="/path/to/cdn/jquery.min.js"></script>
<script src="/path/to/dist/jquery.inputmask.min.js"></script>
<!-- Allows data-input attribute -->
<script src="/path/to/dist/bindings/inputmask.binding.js"></script>

2. Define your masks utilizing data-inputmask attribute. The plugin helps any text fields and occasion content editable factor.

<input data-inputmask="'alias': 'date'" />
<div contenteditable="true" data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false"></div>
<textarea data-inputmask="'mask': '99-9999999'" /></textarea>

3. Call the plugin on the target factor and executed it.

// Vanilla JavaScript
Inputmask().mask(document.querySelectorAll("Selector"));

// jQuery
$("Selector").inputmask();

4. You may also define the input masks within the JavaScript during init.

// Vanilla JavaScript
Inputmask("9-a{1,3}9{1,3}").mask("Selector");

// jQuery
$("Selector").inputmask("99-9999999");

5. All default choices to customize the input masks plugin.

Inputmask({
  // mask placeholder
  placeholder: "_",

  // symbols used to indicate an optional part in the mask
  optionalmarker: [ "[", "]" ],

  // symbols used to indicate a quantifier in the mask
  quantifiermarker: [ "{", "}" ],

  // symbols used to indicate a group in the mask
  groupmarker: [ "(", ")" ],

  // symbols used to indicate an alternator part in the mask
  alternatormarker: "|",

  // symbols used to escape a part in the mask
  escapeChar: "\\",

  // mask here
  mask: null,

  // define your mask using regex
  regex: null, 

  // executes when the mask is complete
  oncomplete: $.noop, 

  // executes when the mask is incomplete and focus is lost
  onincomplete: $.noop, 

  // executes when the mask is cleared
  oncleared: $.noop, 

  // repetitions of the mask: * ~ forever, 
  // otherwise specify an integer
  repeat: 0, 

  // true: allocated buffer for the mask and repetitions
  // false: allocate only if needed
  greedy: true, 

  // automatically unmask when retrieving the value with $.fn.val or value if the browser supports __lookupGetter__ or getOwnPropertyDescriptor
  autoUnmask: false,

  // remove the mask before submitting the form.
  removeMaskOnSubmit: false, 

  // remove the empty mask on blur or when not empty removes the optional trailing part
  clearMaskOnLostFocus: true,

  // insert the input or overwrite the input
  insertMode: true, 

  // clear the incomplete input on blur
  clearIncomplete: false, 

  // extend the masks
  alias: null,

  // callback to implement autocomplete on certain keys for example. 
  // args => event, buffer, caretPos, opts
  onKeyDown: $.noop, 

  // executes before masking the initial value to allow preprocessing of the initial value.  
  // args => initialValue, opts => return processedValue
  onBeforeMask: undefined, 

  // executes before masking the pasted value to allow preprocessing of the pasted value.  
  // args => pastedValue, opts => return processedValue
  onBeforePaste: undefined, 

  // executes before writing to the masked element. 
  // args => event, opts
  onBeforeWrite: undefined, 

  // executes after unmasking to allow postprocessing of the unmaskedvalue.  
  // args => maskedValue, unmaskedValue, opts
  onUnMask: undefined,  

  // show the mask-placeholder when the input has focus
  showMaskOnFocus: true, 

  // show the mask-placeholder when hovering the empty input
  showMaskOnHover: true, 

  // executes on every key-press with the result of isValid. 
  // Params: result, opts
  onKeyValidation: $.noop, 

  // a character which can be used to skip an optional part of a mask
  skipOptionalPartCharacter: " ", 

  // align to the right
  rightAlign: false, 

  // pressing escape reverts the value to the value before focus
  undoOnEscape: true, 

  // numeric basic properties
  radixPoint: "", //".", // | ","

  // numeric basic properties
  groupSeparator: "",

  // try to keep the mask static while typing. 
  // Decisions to alter the mask will be posponed if possible 
  // undefined see auto selection for multi masks
  keepStatic: undefined, 

  // when enabled the caret position is set after the latest valid position on TAB
  positionCaretOnTab: true, 

  // allows for tabbing through the different parts of the masked field
  tabThrough: false, 

  // list with the supported input types
  supportsInputType: ["text", "tel", "password"], 

  // specify keyCodes which should not be considered in the keypress event, otherwise the preventDefault will stop their default behavior especially in FF
  ignorables: [8, 9, 13, 19, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 93, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 0, 229],

  // override for isComplete - args => buffer, opts - return true || false
  isComplete: null, 

  //hook to alter the clear behavior in the stripValidPositions args => maskset, position, lastValidPosition, opts => return true|false/command object
  canClearPosition: $.noop, 

  // hook to preValidate the input.  Usefull for validating regardless the definition.  args => buffer, pos, char, isSelection, opts => return true/false/command object
  preValidation: null, 

  // hook to postValidate the result from isValid. Usefull for validating the entry as a whole.  args => buffer, currentResult, opts => return true/false/json
  postValidation: null, 

  // specify a definitionSymbol for static content, used to make matches for alternators
  staticDefinitionSymbol: undefined, 

  // just in time masking ~ only mask while typing, can n (number), true or false
  jitMasking: false, 

  // return nothing instead of the buffertemplate when the user hasn't entered anything.
  nullable: true, 

  // dev option - testing inputfallback behavior
  inputEventOnly: false, 

  // disable value property patching
  noValuePatching: false, 

  // none, lvp (based on the last valid position (default), radixFocus (position caret to radixpoint on initial click)
  positionCaretOnClick: "lvp", 

  // mask-level casing. Options: null, "upper", "lower" or "title"
  casing: null, 

  // specify the inputmode  - already in place for when browsers will support it
  inputmode: "verbatim", 

  // use the data-inputmask attributes or to ignore them.
  importDataAttributes: true,

  // alter the behavior of the char shifting on entry or deletion
  shiftPositions: true,

  // use prototype definitions
  usePrototypeDefinitions: true,

  // in milliseconds
  validationEventTimeOut: 3000,

})

6. You may also pass the options via data-inputmask-OPTION attributes.

<input data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false" />
<input data-inputmask-clearmaskonlostfocus="false" />
<input data-inputmask="'alias': 'datetime'" />

7. API strategies.

// Get the unmasked value
// Vanilla JavaScript
var input = document.getElementById(selector);
input.inputmask.unmaskedvalue();
// jQuery
$(selector).inputmask('unmaskedvalue');

// Get the default mask value
// Vanilla JavaScript
var input = document.getElementById(selector);
input.inputmask.getemptymask();
// jQuery
$(selector).inputmask("getemptymask");

// Check if the returned value is masked
// Vanilla JavaScript
var input = document.getElementById(selector);
if (input.inputmask.hasMaskedValue())
// jQuery
if ($(Selector).inputmask("hasMaskedValue"));

// Check whether the current value is complete or not
// Vanilla JavaScript
var input = document.getElementById(selector);
if (input.inputmask.isComplete())
// jQuery
if ($(Selector).inputmask("isComplete"));

// Check if is valid
// Vanilla JavaScript
var input = document.getElementById(selector);
if (input.inputmask.isValid())
// jQuery
if ($(Selector).inputmask("isValid"));

// Get the metadata of the actual mask
// Vanilla JavaScript
var input = document.getElementById(selector);
input.inputmask.getmetadata();
// jQuery
$(Selector).inputmask("getmetadatae"));

// Set new values
// Vanilla JavaScript
var input = document.getElementById(selector);
input.inputmask.setValue(Value);
// jQuery
$(Selector).inputmask("setValue", Value));

// Update options
// Vanilla JavaScript
document.querySelector(Selector).inputmask.option({
  onBeforePaste: function (pastedValue, opts) {
    return phoneNumOnPaste(pastedValue, opts);
  }
});
// jQuery
$("Selector").inputmask("option", {
  onBeforePaste: function (pastedValue, opts) {
    return phoneNumOnPaste(pastedValue, opts);
  }
})

// Format given values
// Set new values
// Vanilla JavaScript
Inputmask.format("2331973", { alias: "datetime", inputFormat: "dd/mm/yyyy"});
// jQuery
$(Selector).inputmask("format", "2331973"), { alias: "datetime", inputFormat: "dd/mm/yyyy"});

// Remove the inputmask
var input = document.getElementById(selector);
input.inputmask.remove();
// jQuery
$(selector).inputmask("remove");

Easy JavaScript/jQuery Input Mask Plugin, Inputmask Github, bootstrap input mask, jquery input mask regex, jquery input mask alphanumeric


See Demo And Download

Official Website(RobinHerbots): Click Here

This superior jQuery/javascript plugin is developed by RobinHerbots. For extra Advanced Usages, please go to the official website.

Be First to Comment

    Leave a Reply

    Your email address will not be published. Required fields are marked *