Friday, April 19, 2024
HomejQuerySimple JavaScript/jQuery Enter Masks Plugin - inputmask

Simple JavaScript/jQuery Enter Masks Plugin – inputmask


jQuery Enter Masks is a light-weight and easy-to-use JavaScript/jQuery plugin that makes it simpler to create an enter masks. An enter masks helps the consumer with the enter by making certain a predefined format. This may be helpful for dates, numerics, cellphone numbers, and many others. 

Options:

  • non-compulsory elements anywere within the masks
  • risk to outline aliases which disguise complexity
  • date / datetime masks
  • numeric masks
  • a number of callbacks
  • non-greedy masks
  • many options will be enabled/disabled/configured by choices
  • helps readonly/disabled/dir=”rtl” attributes
  • help data-inputmask attribute
  • multi-mask help
  • can be utilized as a vanilla JavaScript plugin

See Additionally:

The right way to use it:

1. Set up and import the Enter Masks plugin.

# NPM
$ npm set up 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>
<!-- Permits data-input attribute -->
<script src="/path/to/dist/bindings/inputmask.binding.js"></script>

2. Outline your masks utilizing data-inputmask attribute. The plugin helps any textual content fields and occasion content material editable ingredient.

<enter data-inputmask="'alias': 'date'" />
<div contenteditable="true" data-inputmask="'masks': '9', 'repeat': 10, 'grasping' : false"></div>
<textarea data-inputmask="'masks': '99-9999999'" /></textarea>

3. Default masking definitions.

  • 9: numeric
  • a: alphabetical
  • *: alphanumeric

4. Predefined masks alias.

  • datetime
  • numeric
  • cssunit
  • url
  • IP
  • electronic mail
  • mac
  • vin

5. Name the plugin on the goal ingredient and performed.

// Vanilla JavaScript
Inputmask().masks(doc.querySelectorAll("Selector"));

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

6. You can even outline the enter masks within the JavaScript throughout init.

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

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

7. All default choices to customise the enter masks plugin.

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

  // symbols used to point an non-compulsory half within the masks
  optionalmarker: [ "[", "]" ],

  // symbols used to point a quantifier within the masks
  quantifiermarker: [ "{", "}" ],

  // symbols used to point a bunch within the masks
  groupmarker: [ "(", ")" ],

  // symbols used to point an alternator half within the masks
  alternatormarker: "|",

  // symbols used to flee a component within the masks
  escapeChar: "",

  // masks right here
  masks: null,

  // outline your masks utilizing regex
  regex: null, 

  // executes when the masks is full
  oncomplete: $.noop, 

  // executes when the masks is incomplete and focus is misplaced
  onincomplete: $.noop, 

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

  // repetitions of the masks: * ~ ceaselessly, 
  // in any other case specify an integer
  repeat: 0, 

  // true: allotted buffer for the masks and repetitions
  // false: allocate provided that wanted
  grasping: true, 

  // robotically unmask when retrieving the worth with $.fn.val or worth if the browser helps __lookupGetter__ or getOwnPropertyDescriptor
  autoUnmask: false,

  // take away the masks earlier than submitting the shape.
  removeMaskOnSubmit: false, 

  // take away the empty masks on blur or when not empty removes the non-compulsory trailing half
  clearMaskOnLostFocus: true,

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

  // clear the unfinished enter on blur
  clearIncomplete: false, 

  // prolong the masks
  alias: null,

  // callback to implement autocomplete on sure keys for instance. 
  // args => occasion, buffer, caretPos, opts
  onKeyDown: $.noop, 

  // executes earlier than masking the preliminary worth to permit preprocessing of the preliminary worth.  
  // args => initialValue, opts => return processedValue
  onBeforeMask: undefined, 

  // executes earlier than masking the pasted worth to permit preprocessing of the pasted worth.  
  // args => pastedValue, opts => return processedValue
  onBeforePaste: undefined, 

  // executes earlier than writing to the masked ingredient. 
  // args => occasion, opts
  onBeforeWrite: undefined, 

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

  // present the mask-placeholder when the enter has focus
  showMaskOnFocus: true, 

  // present the mask-placeholder when hovering the empty enter
  showMaskOnHover: true, 

  // executes on each key-press with the results of isValid. 
  // Params: consequence, opts
  onKeyValidation: $.noop, 

  // a personality which can be utilized to skip an non-compulsory a part of a masks
  skipOptionalPartCharacter: " ", 

  // align to the precise
  rightAlign: false, 

  // urgent escape reverts the worth to the worth earlier than focus
  undoOnEscape: true, 

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

  // numeric fundamental properties
  groupSeparator: "",

  // attempt to maintain the masks static whereas typing. 
  // Selections to change the masks will likely be posponed if attainable 
  // undefined see auto choice for multi masks
  keepStatic: undefined, 

  // when enabled the caret place is about after the most recent legitimate place on TAB
  positionCaretOnTab: true, 

  // permits for tabbing via the totally different elements of the masked subject
  tabThrough: false, 

  // checklist with the supported enter varieties
  supportsInputType: ["text", "tel", "password"], 

  // specify keyCodes which shouldn't be thought-about within the keypress occasion, in any other case the preventDefault will cease their default habits particularly 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 change the clear habits within the stripValidPositions args => maskset, place, lastValidPosition, opts => return true|false/command object
  canClearPosition: $.noop, 

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

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

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

  // simply in time masking ~ solely masks whereas typing, can n (quantity), true or false
  jitMasking: false, 

  // return nothing as a substitute of the buffertemplate when the consumer hasn't entered something.
  nullable: true, 

  // dev possibility - testing inputfallback habits
  inputEventOnly: false, 

  // disable worth property patching
  noValuePatching: false, 

  // none, lvp (primarily based on the final legitimate place (default), radixFocus (place caret to radixpoint on preliminary click on)
  positionCaretOnClick: "lvp", 

  // mask-level casing. Choices: null, "higher", "decrease" or "title"
  casing: null, 

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

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

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

  // use prototype definitions
  usePrototypeDefinitions: true,

  // in milliseconds
  validationEventTimeOut: 3000,

})

8. You can even go the choices by way of data-inputmask-OPTION attributes

<enter data-inputmask="'masks': '9', 'repeat': 10, 'grasping' : false" />
<enter data-inputmask-clearmaskonlostfocus="false" />
<enter data-inputmask="'alias': 'datetime'" />

9. API strategies.

// Get the unmasked worth
// Vanilla JavaScript
var enter = doc.getElementById(selector);
enter.inputmask.unmaskedvalue();
// jQuery
$(selector).inputmask('unmaskedvalue');

// Get the default masks worth
// Vanilla JavaScript
var enter = doc.getElementById(selector);
enter.inputmask.getemptymask();
// jQuery
$(selector).inputmask("getemptymask");

// Examine if the returned worth is masked
// Vanilla JavaScript
var enter = doc.getElementById(selector);
if (enter.inputmask.hasMaskedValue())
// jQuery
if ($(Selector).inputmask("hasMaskedValue"));

// Examine whether or not the present worth is full or not
// Vanilla JavaScript
var enter = doc.getElementById(selector);
if (enter.inputmask.isComplete())
// jQuery
if ($(Selector).inputmask("isComplete"));

// Examine if is legitimate
// Vanilla JavaScript
var enter = doc.getElementById(selector);
if (enter.inputmask.isValid())
// jQuery
if ($(Selector).inputmask("isValid"));

// Get the metadata of the particular masks
// Vanilla JavaScript
var enter = doc.getElementById(selector);
enter.inputmask.getmetadata();
// jQuery
$(Selector).inputmask("getmetadatae"));

// Set new values
// Vanilla JavaScript
var enter = doc.getElementById(selector);
enter.inputmask.setValue(Worth);
// jQuery
$(Selector).inputmask("setValue", Worth));

// Replace choices
// Vanilla JavaScript
doc.querySelector(Selector).inputmask.possibility({
  onBeforePaste: perform (pastedValue, opts) {
    return phoneNumOnPaste(pastedValue, opts);
  }
});
// jQuery
$("Selector").inputmask("possibility", {
  onBeforePaste: perform (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"});

// Take away the inputmask
var enter = doc.getElementById(selector);
enter.inputmask.take away();
// jQuery
$(selector).inputmask("take away");

Changelog:

v5.0.6beta56 (2022-09-27)

  • Added validationEventTimeOut possibility
  • Consumer Webpack/Terserplugin for minification
  • Repair caret shift with destructive numbers in numeric aliases
  • improve alternation logic
  • replace datetime alias
  • datetime prefillYear possibility
  • Allow/disable prefilling of the yr.
  • Though you may simply over sort the proposed worth with out deleting, many appears to see an issue with the yr prediction.
  • This choices is to disable this characteristic.
  • A number of bugs fastened.

v5.0.6 (2020-09-16)

v5.0.5 (2020-07-10)

  • take away some fn in dependencylib

v5.0.4 (2020-03-04)

  • Add: SetMaxOnOverflow possibility (numeric alias).
  • Replace: datetime alias: add autofill logic to yr, full with present yr, permit stuffed yr be overtyped when min date is offered.
  • Bugs fastened.

v5.0.0 (2020-02-13)

  • Add indian numbering help in numeric alias (indianns alias)
  • Add roundingFN choice to numeric alias. (forex, decimal, …)
  • input-inputmode help by way of inputmode possibility (if supported by browser)
  • Add shortcuts possibility in numeric alias.
  • Add insertModeVisual possibility
  • Bugs fastened.
  • Options up to date.

2019-10-25

v4.0.4 (2019-10-22)

  • add url as supported enter sort
  • rework jit enabled quantifiers
  • restore grasping performance
  • repair focus and mouseenter habits in IE

v3.3.7 (2017-06-09)

  • Added: permit customized operation in casing possibility by callback
  • Up to date: put again Regex alias extension for legacy help #1611
  • Up to date: postvalidation can’t set pos of undefined
  • Up to date: repair undoValue initialization
  • Fastened: Main challenge with regex
  • Fastened: React onChange occasion does not work with Inputmask
  • Fastened: Foreign money digits and delete
  • Fastened: Decimal enhancing issues
  • Fastened: UX drawback with electronic mail masks
  • Fastened: Drive numeric to empty (on blur) with ‘0’ as worth 
  • Fastened: ndxInitializer.shift will not be a perform

v3.3.6 (2017-04-20)

  • Added: noValuePatching possibility 
  • Updates: alternator syntax replace – regex like alternations is now supported (aa|99|AA) ~ aa or 99 or AA
  • Fastened: integer backspace bug when set maxLength attr. 
  • Fastened: Regex with placeholder, not working?
  • Fastened: Visualize common expressions #1040
  • Fastened: Cell phone code replace wanted for Malaysia 
  • Fastened: suffix bug (regression) 
  • Fastened: 29 february of non leap-year

v3.3.2 (2016-09-03)

  • Added ‘casing’: ‘title’
  • efficiency updates
  • changed radixFocus possibility by positionCaretOnClick. Permits alternative for habits of the caret on click on. (none, lvp (default), radixFocus)
  • eliminated nojumps possibility
  • replace cellphone alias implementation
  • enhanced alternation choice
  • change default of positionCaretOnTab to true
  • Fastened: onUnMask will not be being known as
  • Fastened ‘setvalue’ on masks with a suffix ends in suffix being doubled, whereas $.fn.val works high quality
  • Fastened when typing after a set character
  • fixup definitions for cellphone alias
  • Fastened: Cover masks’s objects which have a number of choices
  • repair forex with ” ” as groupseparator
  • Fastened: change addEventListener not fired in IE11
  • Dynamically altering masks primarily based on variety of entered characters
  • Fastened: Enter occasion does not fireplace in IE
  • Fastened: Unable to get property ‘forwardPosition’ of undefined or null reference
  • Fastened Issues with grasping dynamic masks
  • IE11 repair
  • Improve caret positioning on click on
  • Pasting to masked enter not engaged on Android
  • replace inputfallback + checkval

v3.3.1 (2016-04-20)

  • Fastened Safari Error: RangeError: Most name stack dimension exceeded
  • Fastened Safari Most name stack dimension exceeded when inputmask certain twice
  • Fastened E-mail alias @ => @._ 
  • Fastened Safari date masks – Context change when jquery.valhook fallback is used 
  • including additional choices although possibility methodology => auto apply the masks + add noremask possibility
  • speedup insert and delete from characters
  • higher deal with alternator logic by merging the locators
  • patchValueProperty – allow native worth property patch on IE8/IE9

v3.3.0 (2016-04-05)

  • Fastened E-mail masks not accepting legitimate emails
  • Fastened Deleting character from enter with ‘electronic mail’ alias shifts all knowledge
  • Fastened some occasions like paste & reduce for Vanilla dependencyLib
  • Fastened AutoUnmask not engaged on IE11
  • Fastened E-mail masks incorrectly together with underscore  => allowed as not typed => consequence invalid
  • Fastened Cannot clear worth when choose all and press BACKSPACE in some circumstance
  • Fastened error happens in safari 9.0.3
  • Fastened Paste doesn’t work correctly when utilizing numericInput
  • Fastened “[object Object]” worth after $ingredient.inputmask(‘setvalue’, ”) name
  • Fastened: Misplaced zero whereas changing a digit in group
  • Fastened: RadixFocus drawback
  • Fastened: “0.00” not displayed if “clearMaskOnLostFocus: true”
  • Fastened: Cannot change integer half when it’s “0”
  • Fastened NumericInput possibility cannot deal with 100.00
  • Fastened: IE8 error: Object does not help this property or methodology
  • Fastened: numeric alias produces “0.00” as a substitute of null when cleared out.
  • Fastened: Caret Positioned After Final Decimal Digit Disallows Signal Enter When digits Choice Set
  • Fastened: Clicking on a highlighted masked subject doesn’t set the caret to the primary legitimate place (Chrome)
  • Fastened: ‘alias’: ‘numeric’, zero worth
  • Fastened: Distinguish empty worth and ‘$ 0.00’ worth for forex alias
  • Fastened: validate common expression for indian car registration quantity
  • Fastened: InputMask take away a 0 in left aspect. (numericInput: true)
  • Fastened: min worth challenge
  • Fastened: PostValidation perform fails when utilizing placeholder and digitsOptional is fake
  • enhance getmetadata
  • Added VIN masks
  • Added nullable possibility => change to return the placeholder or null when nothing is entered
  • change funtionality of postValidation => consequence could also be true|false
  • patchValueProperty – allow native worth property patch on IE10/IE11
  • replace negation dealing with for numeric alias

v3.2.7 (2016-01-27)

  • IEMobile fixes
  • favor inputfallback for android
  • Fastened: Situation in Android (Samsung GALAXY S5) 
  • Fastened: time masks, backspace habits on android chrome 
  • Fastened: Android Chrome Browser 
  • Fastened: Masks challenge in Android with Swype Keyboard 
  • Fastened: Pasting to masked enter not engaged on Android 
  • Fastened: Decimal level/comma not engaged on Android 4.4 
  • Fastened: Would not work on Android #1073
  • Fastened: numeric enter in cell #897
  • Fastened: Help for Android default browser #368
  • Fastened: Repeating a personality and a quantity On Cell 
  • Fastened: Inputs are ignored on FF 39 on Android 5.0.2 
  • Fastened: Telephone enter masks duplicates every character on Samsung Android pill
  • Fastened: Help for Android default browser 
  • Fastened: fastened “valids will not be outlined” error 

v3.2.6 (2016-01-25)

  • Added staticDefinitionSymbol
  • Added embody textarea as a legitimate masking ingredient
  • add jitMasking possibility
  • add supportsInputType possibility
  • replace alternation logic
  • implement lacking elements within the jqlite DependencyLib
  • Take away namespaces for occasions (simplifies implementing different dependencyLibs, in addition to jquery)
  • Fastened No-strict masks
  • Fastened Inputmask not work with textarea
  • Fastened Cursor shifted to the RIGHT align any manner
  • Fastened A number of masks
  • Fastened Double enter for submit
  • Fastened A number of Masks Click on Focus Error
  • Fastened IE9 SCRIPT445: Object doesn’t help this motion
  • Fastened Enter masks cannot be utilized on different HTML5 enter varieties
  • Fastened Preliminary worth like VAA will get truncated to V-__ with masks like “I{1,3}-ZZ”
  • Fastened Present placeholder as consumer varieties
  • Fastened IE11 clear not working in emulated IE9 mode
  • Fastened Situation with reset of inputmask subject
  • Fastened ‘405 not allowed’ error on loading phone-codes.js on sure Ajax configuration.
  • enhanced caching in gettests
  • Fastened Home windows Telephone Consumer unable to set Date

v3.2.5 (2015-11-24)

  • Fastened numeric extensions do not supported with vanilla DependencyLib
  • Fastened alias choices from ‘data-inputmask’ will not be used anymore
  • Fastened E-mail masks does not permit to go to the area half by mouse
  • Fastened Foreign money validator provides false destructive if variety of digits in integer half will not be multiplier of groupSize
  • Fastened data-inputmask => masks with optionals not parsed appropriately
  • enhance cursor positioning and placeholder dealing with
  • take away $(“selector”).inputmask(“masks”, { masks: “99-999 …” }) format from plugin

v3.2.4 (2015-11-20)

  • permit passing a selector to the masks perform
  • permit passing a component id to the masks perform
  • Fastened: bower bundle
  • Fastened: autoUnmask not work in latest launch
  • Fastened: Definition {_} throws an exception #1106 => replace readme
  • Fastened: Uncaught TypeError for “proportion” alias 
  • Fastened: Mistaken habits for image delete in ip alias 
  • Fastened: ingredient validation for the vanilla dependencyLib

v3.2.3 (2015-11-09)

  • Add tooltip possibility
  • Enhance dealing with of compositionevents
  • Enhance extendAliases, extendDefinitions, extendDefaults
  • inputmask.binding => automated inputmask binding for html attributes
  • optimize init
  • Fastened additional tooltip property
  • Fastened Numeric aliases insert ‘0’ in enter after clearing if there was fraction half
  • Fastened Clear non-compulsory tail in getvalue.
  • Fastened Every character repeats on Cell
  • Fastened errors in IE8
  • Fastened higher/decrease case dealing with in data-inputmask-*
  • Fastened Double Change motion when urgent Enter in Firefox
  • Fastened CTRL-x / Minimize challenge
  • Fastened Can’t erase enter worth throw masks symbols (Android 4.4, Android 4.2)
  • Fastened escaperegex name

v3.2.2 (2015-10-14)

  • Fastened Lacking comma in bower.json and element.json

v3.2.1 (2015-09-21)

  • fastened jquery.inputmask.bundle.js
  • fastened dependency paths for browserify
  • fastened DependencyLib error in Web Explorer
  • fastened Dynamically switching masks in similar enter field not functioning as anticipated
  • fastened Invalid JSON phone-uk.js
  • fastened subject enter width characters cropped whereas writing
  • fastened Foreign money with autogroup and no digits not working
  • replace recordsdata to be included for bundle.json, bower.json, element.json
  • replace namespace dependencyLib => inputmask.dependencyLib
  • added inputmask.dependencyLib.jquery
  • added inputmask.dependencyLib.jqlite

v3.2.0 (2015-09-04)

  • Fastened: by no means set off ‘enter’ occasion when paste after invoke inputmask 
  • Fastened: Script looping begin when add ‘.’ between decimal values (‘.’ half)
  • Fastened: Dynamic masks with {*} and 0 repeats
  • Fastened: Masks doesn’t alternate again after deleting digit
  • Fastened: Script looping begin when add ‘.’ between decimal values
  • Fastened: Delete key not working correctly
  • Fastened: Chinese language / Japanese characters are unable to masks
  • Fastened: Infinite Loop on IE (v11) when utilizing Japanese IME Keyboard
  • Fastened: Numeric inputMask does not rounds worth
  • Fastened: Decimal looses digits
  • Fastened: Firefox: cursor jumps to the precise when clicking anyplace on the worth
  • Fastened: numeric carret place damaged
  • Fastened: Escape non-compulsory marker, quantifiable marker, alternator marker and backslash not working
  • Fastened: Escape worth is inconsistent after masks
  • Fastened: Add isValueMask choice to help masking worth that not but masks
  • Fastened: updating a worth on onincomplete occasion does not work
  • Fastened: Present handy methodology to unmask worth
  • Fastened: phone-codes.js is lacking when putting in with bower
  • Fastened: Typing 1000 turns into 1.00 utilizing groupSeparator=”.”
  • Fastened: Coming into a interval on a clean ‘numeric’ alias enter not allowed
  • Fastened: Decimal separator conversion
  • Fastened: Auto place cursor at finish of information on focus
  • Fastened: Make numericInput work with advanced masks
  • Fastened: Regression in forex
  • Fastened: On google chrome, can’t use jquery to clone the inputmask management with knowledge and occasions
  • Fastened: Can’t overwrite characters when highlighting the characters to the precise of the decimal
  • Fastened: Decimal masks accepts “123,456.” (RadixPoint with no quantity after it)
  • Fastened: Default Enter key perform getting misplaced on an enter masks textual content subject
  • Fastened: Numeric inputs with default worth are setted to clean when submit the shape
  • Fastened: Focus loop on IE9 with numeric.extensions
  • Fastened: Regression in forex alias
  • Fastened: Set particular inputmask possibility on already initialized management
  • Fastened: Situation utilizing datamask-input attributes and occasion handlers
  • some fixes for numeric alias – stripValidPositions
  • Replace placeholder dealing with
  • separate jquery plugin code from the inputmask core (first step to take away jquery dependency from the inputmask core)
  • Replace placeholder dealing with
  • take away “jquery.” within the naming of the extensions to raised replicate their denpendency
  • take away $.inputmask in favor of inputmask class
  • make auto unmask to help escape character within the center.
  • Added: inputmask class
  • Added: setting defaults / definitions / aliases
  • Added: numeric alias – increment/decrement by ctrl-up/ctrl-down
  • Added: proportion alias
  • Added: numeric alias – spherical values
  • Added: inputmask.unmask

This superior jQuery plugin is developed by RobinHerbots. For extra Superior Usages, please verify the demo web page or go to the official web site.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments