inputmask.js 112 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061
  1. /*
  2. * Input Mask Core
  3. * http://github.com/RobinHerbots/jquery.inputmask
  4. * Copyright (c) 2010 - Robin Herbots
  5. * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
  6. * Version: 0.0.0-dev
  7. */
  8. (function (factory) {
  9. if (typeof define === "function" && define.amd) {
  10. define("inputmask", ["inputmask.dependencyLib"], factory);
  11. } else if (typeof exports === "object") {
  12. module.exports = factory(require("./inputmask.dependencyLib"));
  13. } else {
  14. factory(window.dependencyLib || jQuery);
  15. }
  16. }
  17. (function ($) {
  18. var ua = navigator.userAgent,
  19. mobile = /mobile/i.test(ua),
  20. iemobile = /iemobile/i.test(ua),
  21. iphone = /iphone/i.test(ua) && !iemobile,
  22. android = /android/i.test(ua) && !iemobile;
  23. function Inputmask(alias, options) {
  24. //allow instanciating without new
  25. if (!(this instanceof Inputmask)) {
  26. return new Inputmask(alias, options);
  27. }
  28. if ($.isPlainObject(alias)) {
  29. options = alias;
  30. } else {
  31. options = options || {};
  32. options.alias = alias;
  33. }
  34. this.el = undefined;
  35. //init options
  36. this.opts = $.extend(true, {}, this.defaults, options);
  37. this.noMasksCache = options && options.definitions !== undefined;
  38. this.userOptions = options || {}; //user passed options
  39. this.events = {};
  40. this.dataAttribute = "data-inputmask"; //data attribute prefix used for attribute binding
  41. this.resolveAlias(this.opts.alias, options, this.opts);
  42. }
  43. Inputmask.prototype = {
  44. //options default
  45. defaults: {
  46. placeholder: "_",
  47. optionalmarker: {
  48. start: "[",
  49. end: "]"
  50. },
  51. quantifiermarker: {
  52. start: "{",
  53. end: "}"
  54. },
  55. groupmarker: {
  56. start: "(",
  57. end: ")"
  58. },
  59. alternatormarker: "|",
  60. escapeChar: "\\",
  61. mask: null, //needs tobe null instead of undefined as the extend method does not consider props with the undefined value
  62. oncomplete: $.noop, //executes when the mask is complete
  63. onincomplete: $.noop, //executes when the mask is incomplete and focus is lost
  64. oncleared: $.noop, //executes when the mask is cleared
  65. repeat: 0, //repetitions of the mask: * ~ forever, otherwise specify an integer
  66. greedy: true, //true: allocated buffer for the mask and repetitions - false: allocate only if needed
  67. autoUnmask: false, //automatically unmask when retrieving the value with $.fn.val or value if the browser supports __lookupGetter__ or getOwnPropertyDescriptor
  68. removeMaskOnSubmit: false, //remove the mask before submitting the form.
  69. clearMaskOnLostFocus: true,
  70. insertMode: true, //insert the input or overwrite the input
  71. clearIncomplete: false, //clear the incomplete input on blur
  72. aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js
  73. alias: null,
  74. onKeyDown: $.noop, //callback to implement autocomplete on certain keys for example. args => event, buffer, caretPos, opts
  75. onBeforeMask: null, //executes before masking the initial value to allow preprocessing of the initial value. args => initialValue, opts => return processedValue
  76. onBeforePaste: function (pastedValue, opts) {
  77. return $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask(pastedValue, opts) : pastedValue;
  78. }, //executes before masking the pasted value to allow preprocessing of the pasted value. args => pastedValue, opts => return processedValue
  79. onBeforeWrite: null, //executes before writing to the masked element. args => event, opts
  80. onUnMask: null, //executes after unmasking to allow postprocessing of the unmaskedvalue. args => maskedValue, unmaskedValue, opts
  81. showMaskOnFocus: true, //show the mask-placeholder when the input has focus
  82. showMaskOnHover: true, //show the mask-placeholder when hovering the empty input
  83. onKeyValidation: $.noop, //executes on every key-press with the result of isValid. Params: key, result, opts
  84. skipOptionalPartCharacter: " ", //a character which can be used to skip an optional part of a mask
  85. showTooltip: false, //show the activemask as tooltip
  86. tooltip: undefined, //tooltip to show
  87. numericInput: false, //numericInput input direction style (input shifts to the left while holding the caret position)
  88. rightAlign: false, //align to the right
  89. undoOnEscape: true, //pressing escape reverts the value to the value before focus
  90. //numeric basic properties
  91. radixPoint: "", //".", // | ","
  92. radixPointDefinitionSymbol: undefined, //set the radixPoint definitionSymbol ~ used for awareness of the radixpoint
  93. groupSeparator: "", //",", // | "."
  94. //numeric basic properties
  95. keepStatic: null, //try to keep the mask static while typing. Decisions to alter the mask will be posponed if possible - null see auto selection for multi masks
  96. positionCaretOnTab: true, //when enabled the caret position is set after the latest valid position on TAB
  97. tabThrough: false, //allows for tabbing through the different parts of the masked field
  98. supportsInputType: ["text", "tel", "password"], //list with the supported input types
  99. definitions: {
  100. "9": {
  101. validator: "[0-9]",
  102. cardinality: 1,
  103. definitionSymbol: "*"
  104. },
  105. "a": {
  106. validator: "[A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]",
  107. cardinality: 1,
  108. definitionSymbol: "*"
  109. },
  110. "*": {
  111. validator: "[0-9A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]",
  112. cardinality: 1
  113. }
  114. },
  115. //specify keyCodes which should not be considered in the keypress event, otherwise the preventDefault will stop their default behavior especially in FF
  116. 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],
  117. isComplete: null, //override for isComplete - args => buffer, opts - return true || false
  118. canClearPosition: $.noop, //hook to alter the clear behavior in the stripValidPositions args => maskset, position, lastValidPosition, opts => return true|false
  119. postValidation: null, //hook to postValidate the result from isValid. Usefull for validating the entry as a whole. args => buffer, currentResult, opts => return true/false
  120. staticDefinitionSymbol: undefined, //specify a definitionSymbol for static content, used to make matches for alternators
  121. jitMasking: false, //just in time masking ~ only mask while typing, can n (number), true or false
  122. nullable: true, //return nothing instead of the buffertemplate when the user hasn't entered anything.
  123. inputEventOnly: false, //dev option - testing inputfallback behavior
  124. noValuePatching: false, //dev option - disable value property patching
  125. positionCaretOnClick: "lvp", //none, lvp (based on the last valid position (default), radixFocus (position caret to radixpoint on initial click)
  126. casing: null, //mask-level casing. Options: null, "upper", "lower" or "title"
  127. inputmode: "verbatim", //specify the inputmode - already in place for when browsers will support it
  128. colorMask: false, //enable css styleable mask
  129. androidHack: false //see README_android.md
  130. },
  131. masksCache: {},
  132. mask: function (elems) {
  133. var that = this;
  134. function importAttributeOptions(npt, opts, userOptions, dataAttribute) {
  135. var attrOptions = npt.getAttribute(dataAttribute),
  136. option, dataoptions, optionData, p;
  137. function importOption(option, optionData) {
  138. optionData = optionData !== undefined ? optionData : npt.getAttribute(dataAttribute + "-" + option);
  139. if (optionData !== null) {
  140. if (typeof optionData === "string") {
  141. if (option.indexOf("on") === 0) optionData = window[optionData]; //get function definition
  142. else if (optionData === "false") optionData = false;
  143. else if (optionData === "true") optionData = true;
  144. }
  145. userOptions[option] = optionData;
  146. }
  147. }
  148. if (attrOptions && attrOptions !== "") {
  149. attrOptions = attrOptions.replace(new RegExp("'", "g"), '"');
  150. dataoptions = JSON.parse("{" + attrOptions + "}");
  151. }
  152. //resolve aliases
  153. if (dataoptions) { //pickup alias from dataAttribute
  154. optionData = undefined;
  155. for (p in dataoptions) {
  156. if (p.toLowerCase() === "alias") {
  157. optionData = dataoptions[p];
  158. break;
  159. }
  160. }
  161. }
  162. importOption("alias", optionData); //pickup alias from dataAttribute-alias
  163. if (userOptions.alias) {
  164. that.resolveAlias(userOptions.alias, userOptions, opts);
  165. }
  166. for (option in opts) {
  167. if (dataoptions) {
  168. optionData = undefined;
  169. for (p in dataoptions) {
  170. if (p.toLowerCase() === option.toLowerCase()) {
  171. optionData = dataoptions[p];
  172. break;
  173. }
  174. }
  175. }
  176. importOption(option, optionData);
  177. }
  178. $.extend(true, opts, userOptions);
  179. return opts;
  180. }
  181. if (typeof elems === "string") {
  182. elems = document.getElementById(elems) || document.querySelectorAll(elems);
  183. }
  184. elems = elems.nodeName ? [elems] : elems;
  185. $.each(elems, function (ndx, el) {
  186. var scopedOpts = $.extend(true, {}, that.opts);
  187. importAttributeOptions(el, scopedOpts, $.extend(true, {}, that.userOptions), that.dataAttribute);
  188. var maskset = generateMaskSet(scopedOpts, that.noMasksCache);
  189. if (maskset !== undefined) {
  190. if (el.inputmask !== undefined) {
  191. el.inputmask.remove();
  192. }
  193. //store inputmask instance on the input with element reference
  194. el.inputmask = new Inputmask();
  195. el.inputmask.opts = scopedOpts;
  196. el.inputmask.noMasksCache = that.noMasksCache;
  197. el.inputmask.userOptions = $.extend(true, {}, that.userOptions);
  198. el.inputmask.el = el;
  199. el.inputmask.maskset = maskset;
  200. el.inputmask.isRTL = false;
  201. $.data(el, "_inputmask_opts", scopedOpts);
  202. maskScope({
  203. "action": "mask",
  204. "el": el
  205. });
  206. }
  207. });
  208. return elems && elems[0] ? (elems[0].inputmask || this) : this;
  209. },
  210. option: function (options, noremask) { //set extra options || retrieve value of a current option
  211. if (typeof options === "string") {
  212. return this.opts[options];
  213. } else if (typeof options === "object") {
  214. $.extend(this.userOptions, options); //user passed options
  215. //remask
  216. if (this.el && noremask !== true) {
  217. this.mask(this.el);
  218. }
  219. return this;
  220. }
  221. },
  222. unmaskedvalue: function (value) {
  223. return maskScope({
  224. "action": "unmaskedvalue",
  225. "el": this.el,
  226. "value": value
  227. }, this.el && this.el.inputmask ? this.el.inputmask.maskset : generateMaskSet(this.opts, this.noMasksCache), this.opts);
  228. },
  229. remove: function () {
  230. if (this.el) {
  231. maskScope({
  232. "action": "remove",
  233. "el": this.el
  234. });
  235. this.el.inputmask = undefined; //delete ~ undefined
  236. return this.el;
  237. }
  238. },
  239. getemptymask: function () { //return the default (empty) mask value, usefull for setting the default value in validation
  240. return maskScope({
  241. "action": "getemptymask"
  242. }, this.maskset || generateMaskSet(this.opts, this.noMasksCache), this.opts);
  243. },
  244. hasMaskedValue: function () { //check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value
  245. return !this.opts.autoUnmask;
  246. },
  247. isComplete: function () {
  248. return maskScope({
  249. "action": "isComplete",
  250. "el": this.el //optional
  251. }, this.maskset || generateMaskSet(this.opts, this.noMasksCache), this.opts);
  252. },
  253. getmetadata: function () { //return mask metadata if exists
  254. return maskScope({
  255. "action": "getmetadata"
  256. }, this.maskset || generateMaskSet(this.opts, this.noMasksCache), this.opts);
  257. },
  258. isValid: function (value) {
  259. return maskScope({
  260. "action": "isValid",
  261. "value": value
  262. }, this.maskset || generateMaskSet(this.opts, this.noMasksCache), this.opts);
  263. },
  264. format: function (value, metadata) {
  265. return maskScope({
  266. "action": "format",
  267. "value": value,
  268. "metadata": metadata //true/false getmetadata
  269. }, this.maskset || generateMaskSet(this.opts, this.noMasksCache), this.opts);
  270. },
  271. analyseMask: function (mask, opts) {
  272. var tokenizer = /(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?\})|[^.?*+^${[]()|\\]+|./g,
  273. escaped = false,
  274. currentToken = new MaskToken(),
  275. match,
  276. m,
  277. openenings = [],
  278. maskTokens = [],
  279. openingToken,
  280. currentOpeningToken,
  281. alternator,
  282. lastMatch,
  283. groupToken;
  284. function MaskToken(isGroup, isOptional, isQuantifier, isAlternator) {
  285. this.matches = [];
  286. this.isGroup = isGroup || false;
  287. this.isOptional = isOptional || false;
  288. this.isQuantifier = isQuantifier || false;
  289. this.isAlternator = isAlternator || false;
  290. this.quantifier = {
  291. min: 1,
  292. max: 1
  293. };
  294. }
  295. //test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, casing: null/upper/lower, def: definitionSymbol, placeholder: placeholder, mask: real maskDefinition}
  296. function insertTestDefinition(mtoken, element, position) {
  297. var maskdef = opts.definitions[element];
  298. position = position !== undefined ? position : mtoken.matches.length;
  299. var prevMatch = mtoken.matches[position - 1];
  300. if (maskdef && !escaped) {
  301. maskdef.placeholder = $.isFunction(maskdef.placeholder) ? maskdef.placeholder(opts) : maskdef.placeholder;
  302. var prevalidators = maskdef.prevalidator,
  303. prevalidatorsL = prevalidators ? prevalidators.length : 0;
  304. //handle prevalidators
  305. for (var i = 1; i < maskdef.cardinality; i++) {
  306. var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [],
  307. validator = prevalidator.validator,
  308. cardinality = prevalidator.cardinality;
  309. mtoken.matches.splice(position++, 0, {
  310. fn: validator ? typeof validator === "string" ? new RegExp(validator) : new function () {
  311. this.test = validator;
  312. } : new RegExp("."),
  313. cardinality: cardinality ? cardinality : 1,
  314. optionality: mtoken.isOptional,
  315. newBlockMarker: prevMatch === undefined || prevMatch.def !== (maskdef.definitionSymbol || element),
  316. casing: maskdef.casing,
  317. def: maskdef.definitionSymbol || element,
  318. placeholder: maskdef.placeholder,
  319. nativeDef: element
  320. });
  321. prevMatch = mtoken.matches[position - 1];
  322. }
  323. mtoken.matches.splice(position++, 0, {
  324. fn: maskdef.validator ? typeof maskdef.validator == "string" ? new RegExp(maskdef.validator) : new function () {
  325. this.test = maskdef.validator;
  326. } : new RegExp("."),
  327. cardinality: maskdef.cardinality,
  328. optionality: mtoken.isOptional,
  329. newBlockMarker: prevMatch === undefined || prevMatch.def !== (maskdef.definitionSymbol || element),
  330. casing: maskdef.casing,
  331. def: maskdef.definitionSymbol || element,
  332. placeholder: maskdef.placeholder,
  333. nativeDef: element
  334. });
  335. } else {
  336. mtoken.matches.splice(position++, 0, {
  337. fn: null,
  338. cardinality: 0,
  339. optionality: mtoken.isOptional,
  340. newBlockMarker: prevMatch === undefined || prevMatch.def !== element,
  341. casing: null,
  342. def: opts.staticDefinitionSymbol || element,
  343. placeholder: opts.staticDefinitionSymbol !== undefined ? element : undefined,
  344. nativeDef: element
  345. });
  346. escaped = false;
  347. }
  348. }
  349. function verifyGroupMarker(lastMatch, isOpenGroup) {
  350. if (lastMatch && lastMatch.isGroup) { //this is not a group but a normal mask => convert
  351. lastMatch.isGroup = false;
  352. insertTestDefinition(lastMatch, opts.groupmarker.start, 0);
  353. if (isOpenGroup !== true) {
  354. insertTestDefinition(lastMatch, opts.groupmarker.end);
  355. }
  356. }
  357. }
  358. function maskCurrentToken(m, currentToken, lastMatch, extraCondition) {
  359. if (currentToken.matches.length > 0 && (extraCondition === undefined || extraCondition)) {
  360. lastMatch = currentToken.matches[currentToken.matches.length - 1];
  361. verifyGroupMarker(lastMatch);
  362. }
  363. insertTestDefinition(currentToken, m);
  364. }
  365. function defaultCase() {
  366. if (openenings.length > 0) {
  367. currentOpeningToken = openenings[openenings.length - 1];
  368. maskCurrentToken(m, currentOpeningToken, lastMatch, !currentOpeningToken.isAlternator);
  369. if (currentOpeningToken.isAlternator) { //handle alternator a | b case
  370. alternator = openenings.pop();
  371. for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
  372. alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group
  373. }
  374. if (openenings.length > 0) {
  375. currentOpeningToken = openenings[openenings.length - 1];
  376. currentOpeningToken.matches.push(alternator);
  377. } else {
  378. currentToken.matches.push(alternator);
  379. }
  380. }
  381. } else {
  382. maskCurrentToken(m, currentToken, lastMatch);
  383. }
  384. }
  385. function reverseTokens(maskToken) {
  386. function reverseStatic(st) {
  387. if (st === opts.optionalmarker.start) st = opts.optionalmarker.end;
  388. else if (st === opts.optionalmarker.end) st = opts.optionalmarker.start;
  389. else if (st === opts.groupmarker.start) st = opts.groupmarker.end;
  390. else if (st === opts.groupmarker.end) st = opts.groupmarker.start;
  391. return st;
  392. }
  393. maskToken.matches = maskToken.matches.reverse();
  394. for (var match in maskToken.matches) {
  395. var intMatch = parseInt(match);
  396. if (maskToken.matches[match].isQuantifier && maskToken.matches[intMatch + 1] && maskToken.matches[intMatch + 1].isGroup) { //reposition quantifier
  397. var qt = maskToken.matches[match];
  398. maskToken.matches.splice(match, 1);
  399. maskToken.matches.splice(intMatch + 1, 0, qt);
  400. }
  401. if (maskToken.matches[match].matches !== undefined) {
  402. maskToken.matches[match] = reverseTokens(maskToken.matches[match]);
  403. } else {
  404. maskToken.matches[match] = reverseStatic(maskToken.matches[match]);
  405. }
  406. }
  407. return maskToken;
  408. }
  409. while (match = tokenizer.exec(mask)) {
  410. m = match[0];
  411. if (escaped) {
  412. defaultCase();
  413. continue;
  414. }
  415. switch (m.charAt(0)) {
  416. case opts.escapeChar:
  417. escaped = true;
  418. break;
  419. case opts.optionalmarker.end:
  420. // optional closing
  421. case opts.groupmarker.end:
  422. // Group closing
  423. openingToken = openenings.pop();
  424. if (openingToken !== undefined) {
  425. if (openenings.length > 0) {
  426. currentOpeningToken = openenings[openenings.length - 1];
  427. currentOpeningToken.matches.push(openingToken);
  428. if (currentOpeningToken.isAlternator) { //handle alternator (a) | (b) case
  429. alternator = openenings.pop();
  430. for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
  431. alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group
  432. }
  433. if (openenings.length > 0) {
  434. currentOpeningToken = openenings[openenings.length - 1];
  435. currentOpeningToken.matches.push(alternator);
  436. } else {
  437. currentToken.matches.push(alternator);
  438. }
  439. }
  440. } else {
  441. currentToken.matches.push(openingToken);
  442. }
  443. } else defaultCase();
  444. break;
  445. case opts.optionalmarker.start:
  446. verifyGroupMarker(currentToken.matches[currentToken.matches.length - 1]);
  447. // optional opening
  448. openenings.push(new MaskToken(false, true));
  449. break;
  450. case opts.groupmarker.start:
  451. verifyGroupMarker(currentToken.matches[currentToken.matches.length - 1]);
  452. // Group opening
  453. openenings.push(new MaskToken(true));
  454. break;
  455. case opts.quantifiermarker.start:
  456. //Quantifier
  457. var quantifier = new MaskToken(false, false, true);
  458. m = m.replace(/[{}]/g, "");
  459. var mq = m.split(","),
  460. mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]),
  461. mq1 = mq.length === 1 ? mq0 : (isNaN(mq[1]) ? mq[1] : parseInt(mq[1]));
  462. if (mq1 === "*" || mq1 === "+") {
  463. mq0 = mq1 === "*" ? 0 : 1;
  464. }
  465. quantifier.quantifier = {
  466. min: mq0,
  467. max: mq1
  468. };
  469. if (openenings.length > 0) {
  470. var matches = openenings[openenings.length - 1].matches;
  471. match = matches.pop();
  472. if (!match.isGroup) {
  473. groupToken = new MaskToken(true);
  474. groupToken.matches.push(match);
  475. match = groupToken;
  476. }
  477. matches.push(match);
  478. matches.push(quantifier);
  479. } else {
  480. match = currentToken.matches.pop();
  481. if (!match.isGroup) {
  482. groupToken = new MaskToken(true);
  483. groupToken.matches.push(match);
  484. match = groupToken;
  485. }
  486. currentToken.matches.push(match);
  487. currentToken.matches.push(quantifier);
  488. }
  489. break;
  490. case opts.alternatormarker:
  491. if (openenings.length > 0) {
  492. currentOpeningToken = openenings[openenings.length - 1];
  493. lastMatch = currentOpeningToken.matches.pop();
  494. } else {
  495. lastMatch = currentToken.matches.pop();
  496. }
  497. if (lastMatch.isAlternator) {
  498. openenings.push(lastMatch);
  499. } else {
  500. alternator = new MaskToken(false, false, false, true);
  501. alternator.matches.push(lastMatch);
  502. openenings.push(alternator);
  503. }
  504. break;
  505. default:
  506. defaultCase();
  507. }
  508. }
  509. while (openenings.length > 0) {
  510. openingToken = openenings.pop();
  511. verifyGroupMarker(openingToken, true);
  512. currentToken.matches.push(openingToken);
  513. }
  514. if (currentToken.matches.length > 0) {
  515. lastMatch = currentToken.matches[currentToken.matches.length - 1];
  516. verifyGroupMarker(lastMatch);
  517. maskTokens.push(currentToken);
  518. }
  519. if (opts.numericInput) {
  520. reverseTokens(maskTokens[0]);
  521. }
  522. // console.log(JSON.stringify(maskTokens));
  523. return maskTokens;
  524. },
  525. resolveAlias: function (aliasStr, options, opts) {
  526. var aliasDefinition = opts.aliases[aliasStr];
  527. if (aliasDefinition) {
  528. if (aliasDefinition.alias) this.resolveAlias(aliasDefinition.alias, undefined, opts); //alias is another alias
  529. $.extend(true, opts, aliasDefinition); //merge alias definition in the options
  530. $.extend(true, opts, options); //reapply extra given options
  531. return true;
  532. } else //alias not found - try as mask
  533. if (opts.mask === null) {
  534. opts.mask = aliasStr;
  535. }
  536. return false;
  537. }
  538. };
  539. //apply defaults, definitions, aliases
  540. Inputmask.extendDefaults = function (options) {
  541. $.extend(true, Inputmask.prototype.defaults, options);
  542. };
  543. Inputmask.extendDefinitions = function (definition) {
  544. $.extend(true, Inputmask.prototype.defaults.definitions, definition);
  545. };
  546. Inputmask.extendAliases = function (alias) {
  547. $.extend(true, Inputmask.prototype.defaults.aliases, alias);
  548. };
  549. //static fn on inputmask
  550. Inputmask.format = function (value, options, metadata) {
  551. return Inputmask(options).format(value, metadata);
  552. };
  553. Inputmask.unmask = function (value, options) {
  554. return Inputmask(options).unmaskedvalue(value);
  555. };
  556. Inputmask.isValid = function (value, options) {
  557. return Inputmask(options).isValid(value);
  558. };
  559. Inputmask.remove = function (elems) {
  560. $.each(elems, function (ndx, el) {
  561. if (el.inputmask) el.inputmask.remove();
  562. });
  563. };
  564. Inputmask.escapeRegex = function (str) {
  565. var specials = ["/", ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\", "$", "^"];
  566. return str.replace(new RegExp("(\\" + specials.join("|\\") + ")", "gim"), "\\$1");
  567. };
  568. Inputmask.keyCode = {
  569. ALT: 18,
  570. BACKSPACE: 8,
  571. BACKSPACE_SAFARI: 127,
  572. CAPS_LOCK: 20,
  573. COMMA: 188,
  574. COMMAND: 91,
  575. COMMAND_LEFT: 91,
  576. COMMAND_RIGHT: 93,
  577. CONTROL: 17,
  578. DELETE: 46,
  579. DOWN: 40,
  580. END: 35,
  581. ENTER: 13,
  582. ESCAPE: 27,
  583. HOME: 36,
  584. INSERT: 45,
  585. LEFT: 37,
  586. MENU: 93,
  587. NUMPAD_ADD: 107,
  588. NUMPAD_DECIMAL: 110,
  589. NUMPAD_DIVIDE: 111,
  590. NUMPAD_ENTER: 108,
  591. NUMPAD_MULTIPLY: 106,
  592. NUMPAD_SUBTRACT: 109,
  593. PAGE_DOWN: 34,
  594. PAGE_UP: 33,
  595. PERIOD: 190,
  596. RIGHT: 39,
  597. SHIFT: 16,
  598. SPACE: 32,
  599. TAB: 9,
  600. UP: 38,
  601. WINDOWS: 91,
  602. X: 88
  603. };
  604. function generateMaskSet(opts, nocache) {
  605. function generateMask(mask, metadata, opts) {
  606. if (mask === null || mask === "") {
  607. return undefined;
  608. } else {
  609. if (mask.length === 1 && opts.greedy === false && opts.repeat !== 0) {
  610. opts.placeholder = "";
  611. } //hide placeholder with single non-greedy mask
  612. if (opts.repeat > 0 || opts.repeat === "*" || opts.repeat === "+") {
  613. var repeatStart = opts.repeat === "*" ? 0 : (opts.repeat === "+" ? 1 : opts.repeat);
  614. mask = opts.groupmarker.start + mask + opts.groupmarker.end + opts.quantifiermarker.start + repeatStart + "," + opts.repeat + opts.quantifiermarker.end;
  615. }
  616. // console.log(mask);
  617. var masksetDefinition;
  618. if (Inputmask.prototype.masksCache[mask] === undefined || nocache === true) {
  619. masksetDefinition = {
  620. "mask": mask,
  621. "maskToken": Inputmask.prototype.analyseMask(mask, opts),
  622. "validPositions": {},
  623. "_buffer": undefined,
  624. "buffer": undefined,
  625. "tests": {},
  626. "metadata": metadata,
  627. maskLength: undefined
  628. };
  629. if (nocache !== true) {
  630. Inputmask.prototype.masksCache[opts.numericInput ? mask.split("").reverse().join("") : mask] = masksetDefinition;
  631. masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[opts.numericInput ? mask.split("").reverse().join("") : mask]);
  632. }
  633. } else masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[opts.numericInput ? mask.split("").reverse().join("") : mask]);
  634. return masksetDefinition;
  635. }
  636. }
  637. var ms;
  638. if ($.isFunction(opts.mask)) { //allow mask to be a preprocessing fn - should return a valid mask
  639. opts.mask = opts.mask(opts);
  640. }
  641. if ($.isArray(opts.mask)) {
  642. if (opts.mask.length > 1) {
  643. opts.keepStatic = opts.keepStatic === null ? true : opts.keepStatic; //enable by default when passing multiple masks when the option is not explicitly specified
  644. var altMask = opts.groupmarker.start;
  645. $.each(opts.numericInput ? opts.mask.reverse() : opts.mask, function (ndx, msk) {
  646. if (altMask.length > 1) {
  647. altMask += opts.groupmarker.end + opts.alternatormarker + opts.groupmarker.start;
  648. }
  649. if (msk.mask !== undefined && !$.isFunction(msk.mask)) {
  650. altMask += msk.mask;
  651. } else {
  652. altMask += msk;
  653. }
  654. });
  655. altMask += opts.groupmarker.end;
  656. // console.log(altMask);
  657. return generateMask(altMask, opts.mask, opts);
  658. } else opts.mask = opts.mask.pop();
  659. }
  660. if (opts.mask) {
  661. if (opts.mask.mask !== undefined && !$.isFunction(opts.mask.mask)) {
  662. ms = generateMask(opts.mask.mask, opts.mask, opts);
  663. } else {
  664. ms = generateMask(opts.mask, opts.mask, opts);
  665. }
  666. }
  667. return ms;
  668. };
  669. //masking scope
  670. //actionObj definition see below
  671. function maskScope(actionObj, maskset, opts) {
  672. var isRTL = false,
  673. undoValue,
  674. el, $el,
  675. skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
  676. skipInputEvent = false, //skip when triggered from within inputmask
  677. composition = false,
  678. ignorable = false,
  679. maxLength,
  680. mouseEnter = false,
  681. colorMask;
  682. //maskset helperfunctions
  683. function getMaskTemplate(baseOnInput, minimalPos, includeMode) {
  684. //includeMode true => input, undefined => placeholder, false => mask
  685. minimalPos = minimalPos || 0;
  686. var maskTemplate = [],
  687. ndxIntlzr, pos = 0,
  688. test, testPos, lvp = getLastValidPosition();
  689. maxLength = el !== undefined ? el.maxLength : undefined;
  690. if (maxLength === -1) maxLength = undefined;
  691. do {
  692. if (baseOnInput === true && getMaskSet().validPositions[pos]) {
  693. testPos = getMaskSet().validPositions[pos];
  694. test = testPos.match;
  695. ndxIntlzr = testPos.locator.slice();
  696. maskTemplate.push(includeMode === true ? testPos.input : includeMode === false ? test.nativeDef : getPlaceholder(pos, test));
  697. } else {
  698. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  699. test = testPos.match;
  700. ndxIntlzr = testPos.locator.slice();
  701. if (opts.jitMasking === false || pos < lvp || (Number.isFinite(opts.jitMasking) && opts.jitMasking > pos)) {
  702. maskTemplate.push(includeMode === false ? test.nativeDef : getPlaceholder(pos, test));
  703. }
  704. }
  705. pos++;
  706. } while ((maxLength === undefined || pos < maxLength) && (test.fn !== null || test.def !== "") || minimalPos > pos);
  707. if (maskTemplate[maskTemplate.length - 1] === "") {
  708. maskTemplate.pop(); //drop the last one which is empty
  709. }
  710. getMaskSet().maskLength = pos + 1;
  711. return maskTemplate;
  712. }
  713. function getMaskSet() {
  714. return maskset;
  715. }
  716. function resetMaskSet(soft) {
  717. var maskset = getMaskSet();
  718. maskset.buffer = undefined;
  719. if (soft !== true) {
  720. maskset._buffer = undefined;
  721. maskset.validPositions = {};
  722. maskset.p = 0;
  723. }
  724. }
  725. function getLastValidPosition(closestTo, strict, validPositions) {
  726. var before = -1,
  727. after = -1,
  728. valids = validPositions || getMaskSet().validPositions; //for use in valhook ~ context switch
  729. if (closestTo === undefined) closestTo = -1;
  730. for (var posNdx in valids) {
  731. var psNdx = parseInt(posNdx);
  732. if (valids[psNdx] && (strict || valids[psNdx].match.fn !== null)) {
  733. if (psNdx <= closestTo) before = psNdx;
  734. if (psNdx >= closestTo) after = psNdx;
  735. }
  736. }
  737. return (before !== -1 && (closestTo - before) > 1) || after < closestTo ? before : after;
  738. }
  739. function stripValidPositions(start, end, nocheck, strict) {
  740. function IsEnclosedStatic(pos) {
  741. var posMatch = getMaskSet().validPositions[pos];
  742. if (posMatch !== undefined && posMatch.match.fn === null) {
  743. var prevMatch = getMaskSet().validPositions[pos - 1],
  744. nextMatch = getMaskSet().validPositions[pos + 1];
  745. return prevMatch !== undefined && nextMatch !== undefined;
  746. }
  747. return false;
  748. }
  749. var i, startPos = start,
  750. positionsClone = $.extend(true, {}, getMaskSet().validPositions), needsValidation = false;
  751. getMaskSet().p = start; //needed for alternated position after overtype selection
  752. for (i = end - 1; i >= startPos; i--) { //clear selection
  753. if (getMaskSet().validPositions[i] !== undefined) {
  754. if (nocheck === true ||
  755. ((getMaskSet().validPositions[i].match.optionality || !IsEnclosedStatic(i)) && opts.canClearPosition(getMaskSet(), i, getLastValidPosition(), strict, opts) !== false)) {
  756. delete getMaskSet().validPositions[i];
  757. }
  758. }
  759. }
  760. //clear buffer
  761. resetMaskSet(true);
  762. for (i = startPos + 1; i <= getLastValidPosition();) {
  763. while (getMaskSet().validPositions[startPos] !== undefined) startPos++;
  764. var s = getMaskSet().validPositions[startPos];
  765. if (i < startPos) i = startPos + 1;
  766. // while (getMaskSet().validPositions[i] == undefined) i++;
  767. if ((getMaskSet().validPositions[i] !== undefined || !isMask(i)) && s === undefined) {
  768. var t = getTestTemplate(i);
  769. if (needsValidation === false && positionsClone[startPos] && positionsClone[startPos].match.def === t.match.def) { //obvious match
  770. getMaskSet().validPositions[startPos] = $.extend(true, {}, positionsClone[startPos]);
  771. getMaskSet().validPositions[startPos].input = t.input;
  772. delete getMaskSet().validPositions[i];
  773. i++;
  774. } else if (positionCanMatchDefinition(startPos, t.match.def)) {
  775. if (isValid(startPos, t.input || getPlaceholder(i), true) !== false) {
  776. delete getMaskSet().validPositions[i];
  777. i++;
  778. needsValidation = true;
  779. }
  780. } else if (!isMask(i)) {
  781. i++;
  782. startPos--;
  783. }
  784. startPos++;
  785. } else i++;
  786. }
  787. resetMaskSet(true);
  788. }
  789. function determineTestTemplate(tests, guessNextBest) {
  790. var testPos,
  791. testPositions = tests,
  792. lvp = getLastValidPosition(),
  793. lvTest = getMaskSet().validPositions[lvp] || getTests(0)[0],
  794. lvTestAltArr = (lvTest.alternation !== undefined) ? lvTest.locator[lvTest.alternation].toString().split(",") : [];
  795. for (var ndx = 0; ndx < testPositions.length; ndx++) {
  796. testPos = testPositions[ndx];
  797. if (testPos.match &&
  798. (((opts.greedy && testPos.match.optionalQuantifier !== true) || (testPos.match.optionality === false || testPos.match.newBlockMarker === false) && testPos.match.optionalQuantifier !== true) &&
  799. ((lvTest.alternation === undefined || lvTest.alternation !== testPos.alternation) ||
  800. (testPos.locator[lvTest.alternation] !== undefined && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAltArr))))) {
  801. if (guessNextBest !== true || (testPos.match.fn === null && !/[0-9a-bA-Z]/.test(testPos.match.def)))
  802. break;
  803. }
  804. }
  805. return testPos;
  806. }
  807. function getTestTemplate(pos, ndxIntlzr, tstPs) {
  808. return getMaskSet().validPositions[pos] || determineTestTemplate(getTests(pos, ndxIntlzr ? ndxIntlzr.slice() : ndxIntlzr, tstPs));
  809. }
  810. function getTest(pos) {
  811. if (getMaskSet().validPositions[pos]) {
  812. return getMaskSet().validPositions[pos];
  813. }
  814. return getTests(pos)[0];
  815. }
  816. function positionCanMatchDefinition(pos, def) {
  817. var valid = false,
  818. tests = getTests(pos);
  819. for (var tndx = 0; tndx < tests.length; tndx++) {
  820. if (tests[tndx].match && tests[tndx].match.def === def) {
  821. valid = true;
  822. break;
  823. }
  824. }
  825. return valid;
  826. }
  827. function getTests(pos, ndxIntlzr, tstPs) {
  828. var maskTokens = getMaskSet().maskToken,
  829. testPos = ndxIntlzr ? tstPs : 0,
  830. ndxInitializer = ndxIntlzr ? ndxIntlzr.slice() : [0],
  831. matches = [],
  832. insertStop = false,
  833. latestMatch,
  834. cacheDependency = ndxIntlzr ? ndxIntlzr.join("") : "";
  835. function resolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) { //ndxInitializer contains a set of indexes to speedup searches in the mtokens
  836. function handleMatch(match, loopNdx, quantifierRecurse) {
  837. function isFirstMatch(latestMatch, tokenGroup) {
  838. var firstMatch = $.inArray(latestMatch, tokenGroup.matches) === 0;
  839. if (!firstMatch) {
  840. $.each(tokenGroup.matches, function (ndx, match) {
  841. if (match.isQuantifier === true) {
  842. firstMatch = isFirstMatch(latestMatch, tokenGroup.matches[ndx - 1]);
  843. if (firstMatch) return false;
  844. }
  845. });
  846. }
  847. return firstMatch;
  848. }
  849. function resolveNdxInitializer(pos, alternateNdx, targetAlternation) {
  850. var bestMatch, indexPos;
  851. if (getMaskSet().tests[pos] || getMaskSet().validPositions[pos]) {
  852. $.each(getMaskSet().tests[pos] || [getMaskSet().validPositions[pos]], function (ndx, lmnt) {
  853. var alternation = targetAlternation !== undefined ? targetAlternation : lmnt.alternation,
  854. ndxPos = lmnt.locator[alternation] ? lmnt.locator[alternation].toString().indexOf(alternateNdx) : -1;
  855. if ((indexPos === undefined || ndxPos < indexPos) && ndxPos !== -1) {
  856. bestMatch = lmnt;
  857. indexPos = ndxPos;
  858. }
  859. });
  860. }
  861. return bestMatch ?
  862. bestMatch.locator.slice(bestMatch.alternation + 1) :
  863. targetAlternation !== undefined ? resolveNdxInitializer(pos, alternateNdx) : undefined;
  864. }
  865. function staticCanMatchDefinition(source, target) {
  866. if (source.match.fn === null && target.match.fn !== null) {
  867. return target.match.fn.test(source.match.def, getMaskSet(), pos, false, opts, false);
  868. }
  869. return false;
  870. }
  871. if (testPos > 10000) {
  872. throw "Inputmask: There is probably an error in your mask definition or in the code. Create an issue on github with an example of the mask you are using. " + getMaskSet().mask;
  873. }
  874. if (testPos === pos && match.matches === undefined) {
  875. matches.push({
  876. "match": match,
  877. "locator": loopNdx.reverse(),
  878. "cd": cacheDependency
  879. });
  880. return true;
  881. } else if (match.matches !== undefined) {
  882. if (match.isGroup && quantifierRecurse !== match) { //when a group pass along to the quantifier
  883. match = handleMatch(maskToken.matches[$.inArray(match, maskToken.matches) + 1], loopNdx);
  884. if (match) return true;
  885. } else if (match.isOptional) {
  886. var optionalToken = match;
  887. match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  888. if (match) {
  889. latestMatch = matches[matches.length - 1].match;
  890. if (isFirstMatch(latestMatch, optionalToken)) {
  891. insertStop = true; //insert a stop
  892. testPos = pos; //match the position after the group
  893. } else return true;
  894. }
  895. } else if (match.isAlternator) {
  896. var alternateToken = match,
  897. malternateMatches = [],
  898. maltMatches,
  899. currentMatches = matches.slice(),
  900. loopNdxCnt = loopNdx.length;
  901. var altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1;
  902. if (altIndex === -1 || typeof altIndex === "string") {
  903. var currentPos = testPos,
  904. ndxInitializerClone = ndxInitializer.slice(),
  905. altIndexArr = [],
  906. amndx;
  907. if (typeof altIndex == "string") {
  908. altIndexArr = altIndex.split(",");
  909. } else {
  910. for (amndx = 0; amndx < alternateToken.matches.length; amndx++) {
  911. altIndexArr.push(amndx);
  912. }
  913. }
  914. for (var ndx = 0; ndx < altIndexArr.length; ndx++) {
  915. amndx = parseInt(altIndexArr[ndx]);
  916. matches = [];
  917. //set the correct ndxInitializer
  918. ndxInitializer = resolveNdxInitializer(testPos, amndx, loopNdxCnt) || ndxInitializerClone.slice();
  919. match = handleMatch(alternateToken.matches[amndx] || maskToken.matches[amndx], [amndx].concat(loopNdx), quantifierRecurse) || match;
  920. if (match !== true && match !== undefined && (altIndexArr[altIndexArr.length - 1] < alternateToken.matches.length)) { //no match in the alternations (length mismatch) => look further
  921. var ntndx = $.inArray(match, maskToken.matches) + 1;
  922. if (maskToken.matches.length > ntndx) {
  923. match = handleMatch(maskToken.matches[ntndx], [ntndx].concat(loopNdx.slice(1, loopNdx.length)), quantifierRecurse);
  924. if (match) {
  925. altIndexArr.push(ntndx.toString());
  926. $.each(matches, function (ndx, lmnt) {
  927. lmnt.alternation = loopNdx.length - 1;
  928. });
  929. }
  930. }
  931. }
  932. maltMatches = matches.slice();
  933. testPos = currentPos;
  934. matches = [];
  935. //fuzzy merge matches
  936. for (var ndx1 = 0; ndx1 < maltMatches.length; ndx1++) {
  937. var altMatch = maltMatches[ndx1], hasMatch = false;
  938. altMatch.alternation = altMatch.alternation || loopNdxCnt;
  939. for (var ndx2 = 0; ndx2 < malternateMatches.length; ndx2++) {
  940. var altMatch2 = malternateMatches[ndx2];
  941. //verify equality
  942. if (typeof altIndex !== "string" || $.inArray(altMatch.locator[altMatch.alternation].toString(), altIndexArr) !== -1) {
  943. if (altMatch.match.def === altMatch2.match.def || staticCanMatchDefinition(altMatch, altMatch2)) {
  944. hasMatch = altMatch.match.nativeDef === altMatch2.match.nativeDef;
  945. // if (altMatch.alternation != altMatch2.alternation) {
  946. // console.log("alternation mismatch");
  947. // }
  948. if (altMatch.alternation == altMatch2.alternation && //can we merge if the alternation is different?? TODO TOCHECK INVESTIGATE
  949. altMatch2.locator[altMatch2.alternation].toString().indexOf(altMatch.locator[altMatch.alternation]) === -1) {
  950. altMatch2.locator[altMatch2.alternation] = altMatch2.locator[altMatch2.alternation] + "," + altMatch.locator[altMatch.alternation];
  951. altMatch2.alternation = altMatch.alternation; //we pass the alternation index => used in determineLastRequiredPosition
  952. if (altMatch.match.fn == null) { //staticCanMatchDefinition => set no alternate on match
  953. altMatch2.na = altMatch2.na || altMatch.locator[altMatch.alternation].toString();
  954. if (altMatch2.na.indexOf(altMatch.locator[altMatch.alternation]) === -1)
  955. altMatch2.na = altMatch2.na + "," + altMatch.locator[altMatch.alternation];
  956. }
  957. }
  958. break;
  959. }
  960. }
  961. }
  962. if (!hasMatch) {
  963. malternateMatches.push(altMatch);
  964. }
  965. }
  966. }
  967. if (typeof altIndex == "string") { //filter matches
  968. malternateMatches = $.map(malternateMatches, function (lmnt, ndx) {
  969. if (isFinite(ndx)) {
  970. var mamatch,
  971. alternation = lmnt.alternation,
  972. altLocArr = lmnt.locator[alternation].toString().split(",");
  973. lmnt.locator[alternation] = undefined;
  974. lmnt.alternation = undefined;
  975. for (var alndx = 0; alndx < altLocArr.length; alndx++) {
  976. mamatch = $.inArray(altLocArr[alndx], altIndexArr) !== -1;
  977. if (mamatch) { //rebuild the locator with valid entries
  978. if (lmnt.locator[alternation] !== undefined) {
  979. lmnt.locator[alternation] += ",";
  980. lmnt.locator[alternation] += altLocArr[alndx];
  981. } else lmnt.locator[alternation] = parseInt(altLocArr[alndx]);
  982. lmnt.alternation = alternation;
  983. }
  984. }
  985. if (lmnt.locator[alternation] !== undefined) return lmnt;
  986. }
  987. });
  988. }
  989. matches = currentMatches.concat(malternateMatches);
  990. testPos = pos;
  991. insertStop = matches.length > 0; //insert a stopelemnt when there is an alternate - needed for non-greedy option
  992. //cloneback
  993. ndxInitializer = ndxInitializerClone.slice();
  994. } else {
  995. // if (alternateToken.matches[altIndex]) { //if not in the initial alternation => look further
  996. match = handleMatch(alternateToken.matches[altIndex] || maskToken.matches[altIndex], [altIndex].concat(loopNdx), quantifierRecurse);
  997. // } else match = false;
  998. }
  999. if (match) return true;
  1000. } else if (match.isQuantifier && quantifierRecurse !== maskToken.matches[$.inArray(match, maskToken.matches) - 1]) {
  1001. var qt = match;
  1002. for (var qndx = (ndxInitializer.length > 0) ? ndxInitializer.shift() : 0; (qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max)) && testPos <= pos; qndx++) {
  1003. var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1];
  1004. match = handleMatch(tokenGroup, [qndx].concat(loopNdx), tokenGroup); //set the tokenGroup as quantifierRecurse marker
  1005. if (match) {
  1006. //get latest match
  1007. latestMatch = matches[matches.length - 1].match;
  1008. latestMatch.optionalQuantifier = qndx > (qt.quantifier.min - 1);
  1009. if (isFirstMatch(latestMatch, tokenGroup)) { //search for next possible match
  1010. if (qndx > (qt.quantifier.min - 1)) {
  1011. insertStop = true;
  1012. testPos = pos; //match the position after the group
  1013. break; //stop quantifierloop
  1014. } else return true;
  1015. } else {
  1016. return true;
  1017. }
  1018. }
  1019. }
  1020. } else {
  1021. match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  1022. if (match) return true;
  1023. }
  1024. }
  1025. else
  1026. testPos++;
  1027. }
  1028. for (var tndx = (ndxInitializer.length > 0 ? ndxInitializer.shift() : 0); tndx < maskToken.matches.length; tndx++) {
  1029. if (maskToken.matches[tndx].isQuantifier !== true) {
  1030. var match = handleMatch(maskToken.matches[tndx], [tndx].concat(loopNdx), quantifierRecurse);
  1031. if (match && testPos === pos) {
  1032. return match;
  1033. } else if (testPos > pos) {
  1034. break;
  1035. }
  1036. }
  1037. }
  1038. }
  1039. function mergeLocators(tests) {
  1040. var locator = [];
  1041. if (!$.isArray(tests)) tests = [tests];
  1042. if (tests.length > 0) {
  1043. if (tests[0].alternation === undefined) {
  1044. locator = determineTestTemplate(tests.slice()).locator.slice();
  1045. if (locator.length === 0) locator = tests[0].locator.slice();
  1046. }
  1047. else {
  1048. $.each(tests, function (ndx, tst) {
  1049. if (tst.def !== "") {
  1050. if (locator.length === 0) locator = tst.locator.slice();
  1051. else {
  1052. for (var i = 0; i < locator.length; i++) {
  1053. if (tst.locator[i] && locator[i].toString().indexOf(tst.locator[i]) === -1) {
  1054. locator[i] += "," + tst.locator[i];
  1055. }
  1056. }
  1057. }
  1058. }
  1059. });
  1060. }
  1061. }
  1062. return locator;
  1063. }
  1064. function filterTests(tests) {
  1065. if (opts.keepStatic && pos > 0) {
  1066. if (tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0)) {
  1067. if (tests[0].match.optionality !== true &&
  1068. tests[0].match.optionalQuantifier !== true &&
  1069. tests[0].match.fn === null && !/[0-9a-bA-Z]/.test(tests[0].match.def)) {
  1070. return [determineTestTemplate(tests)];
  1071. }
  1072. }
  1073. }
  1074. return tests;
  1075. }
  1076. if (pos > -1) {
  1077. if (ndxIntlzr === undefined) { //determine index initializer
  1078. var previousPos = pos - 1,
  1079. test;
  1080. while ((test = getMaskSet().validPositions[previousPos] || getMaskSet().tests[previousPos]) === undefined && previousPos > -1) {
  1081. previousPos--;
  1082. }
  1083. if (test !== undefined && previousPos > -1) {
  1084. ndxInitializer = mergeLocators(test);
  1085. cacheDependency = ndxInitializer.join("");
  1086. testPos = previousPos;
  1087. }
  1088. }
  1089. if (getMaskSet().tests[pos] && getMaskSet().tests[pos][0].cd === cacheDependency) { //cacheDependency is set on all tests, just check on the first
  1090. //console.log("cache hit " + pos + " - " + ndxIntlzr);
  1091. return filterTests(getMaskSet().tests[pos]);
  1092. }
  1093. for (var mtndx = ndxInitializer.shift(); mtndx < maskTokens.length; mtndx++) {
  1094. var match = resolveTestFromToken(maskTokens[mtndx], ndxInitializer, [mtndx]);
  1095. if ((match && testPos === pos) || testPos > pos) {
  1096. break;
  1097. }
  1098. }
  1099. }
  1100. if (matches.length === 0 || insertStop) {
  1101. matches.push({
  1102. match: {
  1103. fn: null,
  1104. cardinality: 0,
  1105. optionality: true,
  1106. casing: null,
  1107. def: "",
  1108. placeholder: ""
  1109. },
  1110. locator: [],
  1111. cd: cacheDependency
  1112. });
  1113. }
  1114. if (ndxIntlzr !== undefined && getMaskSet().tests[pos]) { //prioritize full tests for caching
  1115. return filterTests($.extend(true, [], matches));
  1116. }
  1117. getMaskSet().tests[pos] = $.extend(true, [], matches); //set a clone to prevent overwriting some props
  1118. // console.log(pos + " - " + JSON.stringify(matches));
  1119. return filterTests(getMaskSet().tests[pos]);
  1120. }
  1121. function getBufferTemplate() {
  1122. if (getMaskSet()._buffer === undefined) {
  1123. //generate template
  1124. getMaskSet()._buffer = getMaskTemplate(false, 1);
  1125. if (getMaskSet().buffer === undefined) {
  1126. getMaskSet()._buffer.slice();
  1127. }
  1128. }
  1129. return getMaskSet()._buffer;
  1130. }
  1131. function getBuffer(noCache) {
  1132. if (getMaskSet().buffer === undefined || noCache === true) {
  1133. getMaskSet().buffer = getMaskTemplate(true, getLastValidPosition(), true);
  1134. }
  1135. return getMaskSet().buffer;
  1136. }
  1137. function refreshFromBuffer(start, end, buffer) {
  1138. var i;
  1139. if (start === true) {
  1140. resetMaskSet();
  1141. start = 0;
  1142. end = buffer.length;
  1143. } else {
  1144. for (i = start; i < end; i++) {
  1145. delete getMaskSet().validPositions[i];
  1146. }
  1147. }
  1148. for (i = start; i < end; i++) {
  1149. resetMaskSet(true); //prevents clobber from the buffer
  1150. if (buffer[i] !== opts.skipOptionalPartCharacter) {
  1151. isValid(i, buffer[i], true, true);
  1152. }
  1153. }
  1154. }
  1155. function casing(elem, test, pos) {
  1156. switch (opts.casing || test.casing) {
  1157. case "upper":
  1158. elem = elem.toUpperCase();
  1159. break;
  1160. case "lower":
  1161. elem = elem.toLowerCase();
  1162. break;
  1163. case "title":
  1164. var posBefore = getMaskSet().validPositions[pos - 1];
  1165. if (pos === 0 || posBefore && posBefore.input === String.fromCharCode(Inputmask.keyCode.SPACE)) {
  1166. elem = elem.toUpperCase();
  1167. } else {
  1168. elem = elem.toLowerCase();
  1169. }
  1170. break;
  1171. }
  1172. return elem;
  1173. }
  1174. function checkAlternationMatch(altArr1, altArr2) {
  1175. var altArrC = opts.greedy ? altArr2 : altArr2.slice(0, 1),
  1176. isMatch = false;
  1177. for (var alndx = 0; alndx < altArr1.length; alndx++) {
  1178. if ($.inArray(altArr1[alndx], altArrC) !== -1) {
  1179. isMatch = true;
  1180. break;
  1181. }
  1182. }
  1183. return isMatch;
  1184. }
  1185. function isValid(pos, c, strict, fromSetValid, fromAlternate) { //strict true ~ no correction or autofill
  1186. function isSelection(posObj) {
  1187. var selection = isRTL ? (posObj.begin - posObj.end) > 1 || ((posObj.begin - posObj.end) === 1 && opts.insertMode) :
  1188. (posObj.end - posObj.begin) > 1 || ((posObj.end - posObj.begin) === 1 && opts.insertMode);
  1189. return selection && posObj.begin === 0 && posObj.end === getMaskSet().maskLength ? "full" : selection;
  1190. }
  1191. strict = strict === true; //always set a value to strict to prevent possible strange behavior in the extensions
  1192. var maskPos = pos;
  1193. if (pos.begin !== undefined) { //position was a position object - used to handle a delete by typing over a selection
  1194. maskPos = isRTL && !isSelection(pos) ? pos.end : pos.begin;
  1195. }
  1196. function _isValid(position, c, strict) {
  1197. var rslt = false;
  1198. $.each(getTests(position), function (ndx, tst) {
  1199. var test = tst.match,
  1200. loopend = c ? 1 : 0,
  1201. chrs = "";
  1202. for (var i = test.cardinality; i > loopend; i--) {
  1203. chrs += getBufferElement(position - (i - 1));
  1204. }
  1205. if (c) {
  1206. chrs += c;
  1207. }
  1208. //make sure the buffer is set and correct
  1209. getBuffer(true);
  1210. //return is false or a json object => { pos: ??, c: ??} or true
  1211. rslt = test.fn != null ?
  1212. test.fn.test(chrs, getMaskSet(), position, strict, opts, isSelection(pos)) : (c === test.def || c === opts.skipOptionalPartCharacter) && test.def !== "" ? //non mask
  1213. {
  1214. c: test.placeholder || test.def,
  1215. pos: position
  1216. } : false;
  1217. if (rslt !== false) {
  1218. var elem = rslt.c !== undefined ? rslt.c : c;
  1219. elem = (elem === opts.skipOptionalPartCharacter && test.fn === null) ? (test.placeholder || test.def) : elem;
  1220. var validatedPos = position,
  1221. possibleModifiedBuffer = getBuffer();
  1222. if (rslt.remove !== undefined) { //remove position(s)
  1223. if (!$.isArray(rslt.remove)) rslt.remove = [rslt.remove];
  1224. $.each(rslt.remove.sort(function (a, b) {
  1225. return b - a;
  1226. }), function (ndx, lmnt) {
  1227. stripValidPositions(lmnt, lmnt + 1, true);
  1228. });
  1229. }
  1230. if (rslt.insert !== undefined) { //insert position(s)
  1231. if (!$.isArray(rslt.insert)) rslt.insert = [rslt.insert];
  1232. $.each(rslt.insert.sort(function (a, b) {
  1233. return a - b;
  1234. }), function (ndx, lmnt) {
  1235. isValid(lmnt.pos, lmnt.c, true, fromSetValid);
  1236. });
  1237. }
  1238. if (rslt.refreshFromBuffer) {
  1239. var refresh = rslt.refreshFromBuffer;
  1240. strict = true;
  1241. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, possibleModifiedBuffer);
  1242. if (rslt.pos === undefined && rslt.c === undefined) {
  1243. rslt.pos = getLastValidPosition();
  1244. return false; //breakout if refreshFromBuffer && nothing to insert
  1245. }
  1246. validatedPos = rslt.pos !== undefined ? rslt.pos : position;
  1247. if (validatedPos !== position) {
  1248. rslt = $.extend(rslt, isValid(validatedPos, elem, true, fromSetValid)); //revalidate new position strict
  1249. return false;
  1250. }
  1251. } else if (rslt !== true && rslt.pos !== undefined && rslt.pos !== position) { //their is a position offset
  1252. validatedPos = rslt.pos;
  1253. refreshFromBuffer(position, validatedPos, getBuffer().slice());
  1254. if (validatedPos !== position) {
  1255. rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
  1256. return false;
  1257. }
  1258. }
  1259. if (rslt !== true && rslt.pos === undefined && rslt.c === undefined) {
  1260. return false; //breakout if nothing to insert
  1261. }
  1262. if (ndx > 0) {
  1263. resetMaskSet(true);
  1264. }
  1265. if (!setValidPosition(validatedPos, $.extend({}, tst, {
  1266. "input": casing(elem, test, validatedPos)
  1267. }), fromSetValid, isSelection(pos))) {
  1268. rslt = false;
  1269. }
  1270. return false; //break from $.each
  1271. }
  1272. }
  1273. );
  1274. return rslt;
  1275. }
  1276. function alternate(pos, c, strict) {
  1277. var validPsClone = $.extend(true, {}, getMaskSet().validPositions),
  1278. lastAlt,
  1279. alternation,
  1280. isValidRslt = false,
  1281. altPos, prevAltPos, i, validPos, lAltPos = getLastValidPosition(), altNdxs, decisionPos;
  1282. //find last modified alternation
  1283. prevAltPos = getMaskSet().validPositions[lAltPos];
  1284. for (; lAltPos >= 0; lAltPos--) {
  1285. altPos = getMaskSet().validPositions[lAltPos];
  1286. if (altPos && altPos.alternation !== undefined) {
  1287. lastAlt = lAltPos;
  1288. alternation = getMaskSet().validPositions[lastAlt].alternation;
  1289. if (prevAltPos.locator[altPos.alternation] !== altPos.locator[altPos.alternation]) {
  1290. break;
  1291. }
  1292. prevAltPos = altPos;
  1293. }
  1294. }
  1295. if (alternation !== undefined) {
  1296. decisionPos = parseInt(lastAlt);
  1297. var decisionTaker = prevAltPos.locator[prevAltPos.alternation || alternation] !== undefined ? prevAltPos.locator[prevAltPos.alternation || alternation] : altNdxs[0]; //no match in the alternations (length mismatch)
  1298. if (decisionTaker.length > 0) { //no decision taken ~ take first one as decider
  1299. decisionTaker = decisionTaker.split(",")[0];
  1300. }
  1301. var possibilityPos = getMaskSet().validPositions[decisionPos], prevPos = getMaskSet().validPositions[decisionPos - 1];
  1302. $.each(getTests(decisionPos, prevPos ? prevPos.locator : undefined, decisionPos - 1), function (ndx, test) {
  1303. altNdxs = test.locator[alternation] ? test.locator[alternation].toString().split(",") : [];
  1304. for (var mndx = 0; mndx < altNdxs.length; mndx++) {
  1305. var validInputs = [],
  1306. staticInputsBeforePos = 0,
  1307. staticInputsBeforePosAlternate = 0,
  1308. verifyValidInput = false;
  1309. if (decisionTaker < altNdxs[mndx] && (test.na === undefined || $.inArray(altNdxs[mndx], test.na.split(",")) === -1)) {
  1310. getMaskSet().validPositions[decisionPos] = $.extend(true, {}, test);
  1311. var possibilities = getMaskSet().validPositions[decisionPos].locator;
  1312. getMaskSet().validPositions[decisionPos].locator[alternation] = parseInt(altNdxs[mndx]); //set forced decision
  1313. if (test.match.fn == null) {
  1314. if (possibilityPos.input !== test.match.def) {
  1315. verifyValidInput = true; //verify that the new definition matches the input
  1316. if (possibilityPos.generatedInput !== true) {
  1317. validInputs.push(possibilityPos.input);
  1318. }
  1319. }
  1320. staticInputsBeforePosAlternate++;
  1321. getMaskSet().validPositions[decisionPos].generatedInput = !/[0-9a-bA-Z]/.test(test.match.def);
  1322. getMaskSet().validPositions[decisionPos].input = test.match.def;
  1323. } else {
  1324. getMaskSet().validPositions[decisionPos].input = possibilityPos.input;
  1325. }
  1326. for (i = decisionPos + 1; i < getLastValidPosition(undefined, true) + 1; i++) {
  1327. validPos = getMaskSet().validPositions[i];
  1328. if (validPos && validPos.generatedInput !== true && /[0-9a-bA-Z]/.test(validPos.input)) {
  1329. validInputs.push(validPos.input);
  1330. } else if (i < pos) staticInputsBeforePos++;
  1331. delete getMaskSet().validPositions[i];
  1332. }
  1333. if (verifyValidInput && validInputs[0] === test.match.def) {
  1334. validInputs.shift();
  1335. }
  1336. resetMaskSet(true); //clear getbuffer
  1337. isValidRslt = true;
  1338. while (validInputs.length > 0) {
  1339. var input = validInputs.shift();
  1340. if (input !== opts.skipOptionalPartCharacter) {
  1341. if (!(isValidRslt = isValid(getLastValidPosition(undefined, true) + 1, input, false, fromSetValid, true))) {
  1342. break;
  1343. }
  1344. }
  1345. }
  1346. if (isValidRslt) {
  1347. getMaskSet().validPositions[decisionPos].locator = possibilities; //reset forceddecision ~ needed for proper delete
  1348. var targetLvp = getLastValidPosition(pos) + 1;
  1349. for (i = decisionPos + 1; i < getLastValidPosition() + 1; i++) {
  1350. validPos = getMaskSet().validPositions[i];
  1351. if ((validPos === undefined || validPos.match.fn == null) && i < (pos + (staticInputsBeforePosAlternate - staticInputsBeforePos))) {
  1352. staticInputsBeforePosAlternate++;
  1353. }
  1354. }
  1355. pos = pos + (staticInputsBeforePosAlternate - staticInputsBeforePos);
  1356. isValidRslt = isValid(pos > targetLvp ? targetLvp : pos, c, strict, fromSetValid, true);
  1357. }
  1358. if (!isValidRslt) {
  1359. resetMaskSet();
  1360. getMaskSet().validPositions = $.extend(true, {}, validPsClone);
  1361. } else return false; //exit $.each
  1362. }
  1363. }
  1364. });
  1365. }
  1366. return isValidRslt;
  1367. }
  1368. //set alternator choice on previous skipped placeholder positions
  1369. function trackbackAlternations(originalPos, newPos) {
  1370. var vp = getMaskSet().validPositions[newPos];
  1371. if (vp) {
  1372. var targetLocator = vp.locator,
  1373. tll = targetLocator.length;
  1374. for (var ps = originalPos; ps < newPos; ps++) {
  1375. if (getMaskSet().validPositions[ps] === undefined && !isMask(ps, true)) {
  1376. var tests = getTests(ps),
  1377. bestMatch = tests[0],
  1378. equality = -1;
  1379. $.each(tests, function (ndx, tst) { //find best matching
  1380. for (var i = 0; i < tll; i++) {
  1381. if (tst.locator[i] !== undefined && checkAlternationMatch(tst.locator[i].toString().split(","), targetLocator[i].toString().split(","))) {
  1382. if (equality < i) {
  1383. equality = i;
  1384. bestMatch = tst;
  1385. }
  1386. } else break;
  1387. }
  1388. });
  1389. setValidPosition(ps, $.extend({}, bestMatch, {
  1390. "input": bestMatch.match.placeholder || bestMatch.match.def
  1391. }), true);
  1392. }
  1393. }
  1394. }
  1395. }
  1396. function setValidPosition(pos, validTest, fromSetValid, isSelection) {
  1397. if (isSelection || (opts.insertMode && getMaskSet().validPositions[pos] !== undefined && fromSetValid === undefined)) {
  1398. //reposition & revalidate others
  1399. var positionsClone = $.extend(true, {}, getMaskSet().validPositions),
  1400. lvp = getLastValidPosition(undefined, true),
  1401. i;
  1402. for (i = pos; i <= lvp; i++) { //clear selection
  1403. delete getMaskSet().validPositions[i];
  1404. }
  1405. getMaskSet().validPositions[pos] = $.extend(true, {}, validTest);
  1406. var valid = true,
  1407. j, vps = getMaskSet().validPositions, needsValidation = false,
  1408. initialLength = getMaskSet().maskLength;
  1409. for (i = (j = pos); i <= lvp; i++) {
  1410. var t = positionsClone[i];
  1411. if (t !== undefined) {
  1412. var posMatch = j;
  1413. while (posMatch < getMaskSet().maskLength && ((t.match.fn == null && vps[i] && (vps[i].match.optionalQuantifier === true || vps[i].match.optionality === true)) || t.match.fn != null)) {
  1414. posMatch++;
  1415. if (needsValidation === false && positionsClone[posMatch] && positionsClone[posMatch].match.def === t.match.def) { //obvious match
  1416. getMaskSet().validPositions[posMatch] = $.extend(true, {}, positionsClone[posMatch]);
  1417. getMaskSet().validPositions[posMatch].input = t.input;
  1418. fillMissingNonMask(posMatch);
  1419. j = posMatch;
  1420. valid = true;
  1421. } else if (positionCanMatchDefinition(posMatch, t.match.def)) { //validated match
  1422. var result = isValid(posMatch, t.input, true, true);
  1423. valid = result !== false;
  1424. j = (result.caret || result.insert) ? getLastValidPosition() : posMatch;
  1425. needsValidation = true;
  1426. } else {
  1427. valid = t.generatedInput === true;
  1428. }
  1429. if (getMaskSet().maskLength < initialLength) getMaskSet().maskLength = initialLength; //a bit hacky but the masklength is corrected later on
  1430. if (valid) break;
  1431. }
  1432. }
  1433. if (!valid) break;
  1434. }
  1435. if (!valid) {
  1436. getMaskSet().validPositions = $.extend(true, {}, positionsClone);
  1437. resetMaskSet(true);
  1438. return false;
  1439. }
  1440. }
  1441. else
  1442. getMaskSet().validPositions[pos] = $.extend(true, {}, validTest);
  1443. ;
  1444. resetMaskSet(true);
  1445. return true;
  1446. }
  1447. function fillMissingNonMask(maskPos) {
  1448. //Check for a nonmask before the pos
  1449. //find previous valid
  1450. for (var pndx = maskPos - 1; pndx > -1; pndx--) {
  1451. if (getMaskSet().validPositions[pndx]) break;
  1452. }
  1453. ////fill missing nonmask and valid placeholders
  1454. var testTemplate, testsFromPos;
  1455. for (pndx++; pndx < maskPos; pndx++) {
  1456. if (getMaskSet().validPositions[pndx] === undefined && (opts.jitMasking === false || opts.jitMasking > pndx)) {
  1457. testsFromPos = getTests(pndx, getTestTemplate(pndx - 1).locator, pndx - 1).slice();
  1458. if (testsFromPos[testsFromPos.length - 1].match.def === "") testsFromPos.pop();
  1459. testTemplate = determineTestTemplate(testsFromPos);
  1460. if (testTemplate && (testTemplate.match.def === opts.radixPointDefinitionSymbol || !isMask(pndx, true) ||
  1461. ($.inArray(opts.radixPoint, getBuffer()) < pndx && testTemplate.match.fn && testTemplate.match.fn.test(getPlaceholder(pndx), getMaskSet(), pndx, false, opts)))) {
  1462. result = _isValid(pndx, testTemplate.match.placeholder || (testTemplate.match.fn == null ? testTemplate.match.def : (getPlaceholder(pndx) !== "" ? getPlaceholder(pndx) : getBuffer()[pndx])), true);
  1463. if (result !== false) {
  1464. getMaskSet().validPositions[result.pos || pndx].generatedInput = true;
  1465. }
  1466. }
  1467. }
  1468. }
  1469. }
  1470. var result = false,
  1471. positionsClone = $.extend(true, {}, getMaskSet().validPositions); //clone the currentPositions
  1472. fillMissingNonMask(maskPos);
  1473. if (isSelection(pos)) {
  1474. handleRemove(undefined, Inputmask.keyCode.DELETE, pos);
  1475. maskPos = getMaskSet().p;
  1476. }
  1477. if (maskPos < getMaskSet().maskLength) {
  1478. result = _isValid(maskPos, c, strict);
  1479. if ((!strict || fromSetValid === true) && result === false) {
  1480. var currentPosValid = getMaskSet().validPositions[maskPos];
  1481. if (currentPosValid && currentPosValid.match.fn === null && (currentPosValid.match.def === c || c === opts.skipOptionalPartCharacter)) {
  1482. result = {
  1483. "caret": seekNext(maskPos)
  1484. };
  1485. } else if ((opts.insertMode || getMaskSet().validPositions[seekNext(maskPos)] === undefined) && !isMask(maskPos, true)) { //does the input match on a further position?
  1486. var testsFromPos = getTests(maskPos).slice();
  1487. if (testsFromPos[testsFromPos.length - 1].match.def === "") testsFromPos.pop();
  1488. var staticChar = determineTestTemplate(testsFromPos, true);
  1489. if (staticChar && staticChar.match.fn === null) {
  1490. staticChar = staticChar.match.placeholder || staticChar.match.def;
  1491. _isValid(maskPos, staticChar, strict);
  1492. getMaskSet().validPositions[maskPos].generatedInput = true;
  1493. }
  1494. for (var nPos = maskPos + 1, snPos = seekNext(maskPos); nPos <= snPos; nPos++) {
  1495. result = _isValid(nPos, c, strict);
  1496. if (result !== false) {
  1497. trackbackAlternations(maskPos, result.pos !== undefined ? result.pos : nPos);
  1498. maskPos = nPos;
  1499. break;
  1500. }
  1501. }
  1502. }
  1503. }
  1504. }
  1505. if (result === false && opts.keepStatic && !strict && fromAlternate !== true) { //try fuzzy alternator logic
  1506. result = alternate(maskPos, c, strict);
  1507. }
  1508. if (result === true) {
  1509. result = {
  1510. "pos": maskPos
  1511. };
  1512. }
  1513. if ($.isFunction(opts.postValidation) && result !== false && !strict && fromSetValid !== true) {
  1514. result = opts.postValidation(getBuffer(true), result, opts) ? result : false;
  1515. }
  1516. if (result.pos === undefined) {
  1517. result.pos = maskPos;
  1518. }
  1519. if (result === false) {
  1520. resetMaskSet(true);
  1521. getMaskSet().validPositions = $.extend(true, {}, positionsClone); //revert validation changes
  1522. }
  1523. return result;
  1524. }
  1525. function isMask(pos, strict) {
  1526. var test;
  1527. if (strict) {
  1528. test = getTestTemplate(pos).match;
  1529. if (test.def === "") test = getTest(pos).match;
  1530. } else test = getTest(pos).match;
  1531. if (test.fn != null) {
  1532. return test.fn;
  1533. } else if (strict !== true && pos > -1) {
  1534. var tests = getTests(pos);
  1535. return tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0);
  1536. }
  1537. return false;
  1538. }
  1539. function seekNext(pos, newBlock) {
  1540. var maskL = getMaskSet().maskLength;
  1541. if (pos >= maskL) return maskL;
  1542. var position = pos;
  1543. while (++position < maskL &&
  1544. ((newBlock === true && (getTest(position).match.newBlockMarker !== true || !isMask(position))) ||
  1545. (newBlock !== true && !isMask(position)))) {
  1546. }
  1547. return position;
  1548. }
  1549. function seekPrevious(pos, newBlock) {
  1550. var position = pos, tests;
  1551. if (position <= 0) return 0;
  1552. while (--position > 0 &&
  1553. ((newBlock === true && getTest(position).match.newBlockMarker !== true) ||
  1554. (newBlock !== true && !isMask(position) &&
  1555. (tests = getTests(position), tests.length < 2 || (tests.length === 2 && tests[1].match.def === ""))))) {
  1556. }
  1557. return position;
  1558. }
  1559. function getBufferElement(position) {
  1560. return getMaskSet().validPositions[position] === undefined ? getPlaceholder(position) : getMaskSet().validPositions[position].input;
  1561. }
  1562. function writeBuffer(input, buffer, caretPos, event, triggerInputEvent) {
  1563. if (event && $.isFunction(opts.onBeforeWrite)) {
  1564. var result = opts.onBeforeWrite(event, buffer, caretPos, opts);
  1565. if (result) {
  1566. if (result.refreshFromBuffer) {
  1567. var refresh = result.refreshFromBuffer;
  1568. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer || buffer);
  1569. buffer = getBuffer(true);
  1570. }
  1571. //only alter when intented !== undefined
  1572. if (caretPos !== undefined) caretPos = result.caret !== undefined ? result.caret : caretPos;
  1573. }
  1574. }
  1575. input.inputmask._valueSet(buffer.join(""));
  1576. if (caretPos !== undefined && (event === undefined || event.type !== "blur")) {
  1577. caret(input, caretPos);
  1578. } else renderColorMask(input, buffer, caretPos);
  1579. if (triggerInputEvent === true) {
  1580. skipInputEvent = true;
  1581. $(input).trigger("input");
  1582. }
  1583. }
  1584. function getPlaceholder(pos, test) {
  1585. test = test || getTest(pos).match;
  1586. if (test.placeholder !== undefined) {
  1587. return test.placeholder;
  1588. } else if (test.fn === null) {
  1589. if (pos > -1 && getMaskSet().validPositions[pos] === undefined) {
  1590. var tests = getTests(pos),
  1591. staticAlternations = [],
  1592. prevTest;
  1593. if (tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0)) {
  1594. for (var i = 0; i < tests.length; i++) {
  1595. if (tests[i].match.optionality !== true && tests[i].match.optionalQuantifier !== true &&
  1596. (tests[i].match.fn === null || (prevTest === undefined || tests[i].match.fn.test(prevTest.match.def, getMaskSet(), pos, true, opts) !== false))) {
  1597. staticAlternations.push(tests[i]);
  1598. if (tests[i].match.fn === null) prevTest = tests[i];
  1599. if (staticAlternations.length > 1) {
  1600. if (/[0-9a-bA-Z]/.test(staticAlternations[0].match.def)) {
  1601. return opts.placeholder.charAt(pos % opts.placeholder.length);
  1602. }
  1603. }
  1604. }
  1605. }
  1606. }
  1607. }
  1608. return test.def;
  1609. }
  1610. return opts.placeholder.charAt(pos % opts.placeholder.length);
  1611. }
  1612. function checkVal(input, writeOut, strict, nptvl, initiatingEvent, stickyCaret) {
  1613. var inputValue = nptvl.slice(),
  1614. charCodes = "",
  1615. initialNdx = 0, result = undefined;
  1616. function isTemplateMatch() {
  1617. var isMatch = false;
  1618. var charCodeNdx = getBufferTemplate().slice(initialNdx, seekNext(initialNdx)).join("").indexOf(charCodes);
  1619. if (charCodeNdx !== -1 && !isMask(initialNdx)) {
  1620. isMatch = true;
  1621. var bufferTemplateArr = getBufferTemplate().slice(initialNdx, initialNdx + charCodeNdx);
  1622. for (var i = 0; i < bufferTemplateArr.length; i++) {
  1623. if (bufferTemplateArr[i] !== " ") {
  1624. isMatch = false;
  1625. break;
  1626. }
  1627. }
  1628. }
  1629. return isMatch;
  1630. }
  1631. resetMaskSet();
  1632. getMaskSet().p = seekNext(-1);
  1633. // if (writeOut) input.inputmask._valueSet(""); //initial clear
  1634. if (!strict) {
  1635. if (opts.autoUnmask !== true) {
  1636. var staticInput = getBufferTemplate().slice(0, seekNext(-1)).join(""),
  1637. matches = inputValue.join("").match(new RegExp("^" + Inputmask.escapeRegex(staticInput), "g"));
  1638. if (matches && matches.length > 0) {
  1639. inputValue.splice(0, matches.length * staticInput.length);
  1640. initialNdx = seekNext(initialNdx);
  1641. }
  1642. } else {
  1643. initialNdx = seekNext(initialNdx);
  1644. }
  1645. }
  1646. $.each(inputValue, function (ndx, charCode) {
  1647. if (charCode !== undefined) { //inputfallback strips some elements out of the inputarray. $.each logically presents them as undefined
  1648. var keypress = new $.Event("keypress");
  1649. keypress.which = charCode.charCodeAt(0);
  1650. charCodes += charCode;
  1651. var lvp = getLastValidPosition(undefined, true),
  1652. lvTest = getMaskSet().validPositions[lvp],
  1653. nextTest = getTestTemplate(lvp + 1, lvTest ? lvTest.locator.slice() : undefined, lvp);
  1654. if (!isTemplateMatch() || strict || opts.autoUnmask) {
  1655. var pos = strict ? ndx : (nextTest.match.fn == null && nextTest.match.optionality && (lvp + 1) < getMaskSet().p ? lvp + 1 : getMaskSet().p);
  1656. result = keypressEvent.call(input, keypress, true, false, strict, pos);
  1657. initialNdx = pos + 1;
  1658. charCodes = "";
  1659. } else {
  1660. result = keypressEvent.call(input, keypress, true, false, true, lvp + 1);
  1661. }
  1662. if (!strict && $.isFunction(opts.onBeforeWrite)) {
  1663. result = opts.onBeforeWrite(keypress, getBuffer(), result.forwardPosition, opts);
  1664. if (result && result.refreshFromBuffer) {
  1665. var refresh = result.refreshFromBuffer;
  1666. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer);
  1667. resetMaskSet(true);
  1668. if (result.caret) {
  1669. getMaskSet().p = result.caret;
  1670. }
  1671. }
  1672. }
  1673. }
  1674. });
  1675. if (writeOut) {
  1676. var caretPos = undefined, lvp = getLastValidPosition();
  1677. if (document.activeElement === input && (initiatingEvent || result)) {
  1678. caretPos = caret(input).begin;
  1679. if (initiatingEvent && result === false) caretPos = seekNext(getLastValidPosition(caretPos));
  1680. if (result && stickyCaret !== true && (caretPos < lvp + 1 || lvp === -1))
  1681. caretPos = (opts.numericInput && result.caret === undefined) ? seekPrevious(result.forwardPosition) : result.forwardPosition;
  1682. }
  1683. writeBuffer(input, getBuffer(), caretPos, initiatingEvent || new $.Event("checkval"));
  1684. }
  1685. }
  1686. function unmaskedvalue(input) {
  1687. if (input && input.inputmask === undefined) {
  1688. return input.value;
  1689. }
  1690. var umValue = [],
  1691. vps = getMaskSet().validPositions;
  1692. for (var pndx in vps) {
  1693. if (vps[pndx].match && vps[pndx].match.fn != null) {
  1694. umValue.push(vps[pndx].input);
  1695. }
  1696. }
  1697. var unmaskedValue = umValue.length === 0 ? "" : (isRTL ? umValue.reverse() : umValue).join("");
  1698. if ($.isFunction(opts.onUnMask)) {
  1699. var bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join("");
  1700. unmaskedValue = (opts.onUnMask(bufferValue, unmaskedValue, opts) || unmaskedValue);
  1701. }
  1702. return unmaskedValue;
  1703. }
  1704. function caret(input, begin, end, notranslate) {
  1705. function translatePosition(pos) {
  1706. if (notranslate !== true && isRTL && typeof pos === "number" && (!opts.greedy || opts.placeholder !== "")) {
  1707. var bffrLght = getBuffer().join("").length; //join is needed because sometimes we get an empty buffer element which must not be counted for the caret position (numeric alias)
  1708. pos = bffrLght - pos;
  1709. }
  1710. return pos;
  1711. }
  1712. var range;
  1713. if (typeof begin === "number") {
  1714. begin = translatePosition(begin);
  1715. end = translatePosition(end);
  1716. end = (typeof end == "number") ? end : begin;
  1717. // if (!$(input).is(":visible")) {
  1718. // return;
  1719. // }
  1720. var scrollCalc = parseInt(((input.ownerDocument.defaultView || window).getComputedStyle ? (input.ownerDocument.defaultView || window).getComputedStyle(input, null) : input.currentStyle).fontSize) * end;
  1721. input.scrollLeft = scrollCalc > input.scrollWidth ? scrollCalc : 0;
  1722. if (!mobile && opts.insertMode === false && begin === end) end++; //set visualization for insert/overwrite mode
  1723. if (input.setSelectionRange) {
  1724. input.selectionStart = begin;
  1725. input.selectionEnd = end;
  1726. } else if (window.getSelection) {
  1727. range = document.createRange();
  1728. if (input.firstChild === undefined || input.firstChild === null) {
  1729. var textNode = document.createTextNode("");
  1730. input.appendChild(textNode);
  1731. }
  1732. range.setStart(input.firstChild, begin < input.inputmask._valueGet().length ? begin : input.inputmask._valueGet().length);
  1733. range.setEnd(input.firstChild, end < input.inputmask._valueGet().length ? end : input.inputmask._valueGet().length);
  1734. range.collapse(true);
  1735. var sel = window.getSelection();
  1736. sel.removeAllRanges();
  1737. sel.addRange(range);
  1738. //input.focus();
  1739. } else if (input.createTextRange) {
  1740. range = input.createTextRange();
  1741. range.collapse(true);
  1742. range.moveEnd("character", end);
  1743. range.moveStart("character", begin);
  1744. range.select();
  1745. }
  1746. renderColorMask(input, undefined, {begin: begin, end: end});
  1747. } else {
  1748. if (input.setSelectionRange) {
  1749. begin = input.selectionStart;
  1750. end = input.selectionEnd;
  1751. } else if (window.getSelection) {
  1752. range = window.getSelection().getRangeAt(0);
  1753. if (range.commonAncestorContainer.parentNode === input || range.commonAncestorContainer === input) {
  1754. begin = range.startOffset;
  1755. end = range.endOffset;
  1756. }
  1757. } else if (document.selection && document.selection.createRange) {
  1758. range = document.selection.createRange();
  1759. begin = 0 - range.duplicate().moveStart("character", -input.inputmask._valueGet().length);
  1760. end = begin + range.text.length;
  1761. }
  1762. /*eslint-disable consistent-return */
  1763. return {
  1764. "begin": translatePosition(begin),
  1765. "end": translatePosition(end)
  1766. };
  1767. /*eslint-enable consistent-return */
  1768. }
  1769. }
  1770. function determineLastRequiredPosition(returnDefinition) {
  1771. var buffer = getBuffer(),
  1772. bl = buffer.length,
  1773. pos, lvp = getLastValidPosition(),
  1774. positions = {},
  1775. lvTest = getMaskSet().validPositions[lvp],
  1776. ndxIntlzr = lvTest !== undefined ? lvTest.locator.slice() : undefined,
  1777. testPos;
  1778. for (pos = lvp + 1; pos < buffer.length; pos++) {
  1779. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  1780. ndxIntlzr = testPos.locator.slice();
  1781. positions[pos] = $.extend(true, {}, testPos);
  1782. }
  1783. var lvTestAlt = lvTest && lvTest.alternation !== undefined ? lvTest.locator[lvTest.alternation] : undefined;
  1784. for (pos = bl - 1; pos > lvp; pos--) {
  1785. testPos = positions[pos];
  1786. if ((testPos.match.optionality ||
  1787. testPos.match.optionalQuantifier ||
  1788. (lvTestAlt && ((lvTestAlt !== positions[pos].locator[lvTest.alternation] && testPos.match.fn != null) ||
  1789. (testPos.match.fn === null && testPos.locator[lvTest.alternation] && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAlt.toString().split(",")) && getTests(pos)[0].def !== "")))) && buffer[pos] === getPlaceholder(pos, testPos.match)) {
  1790. bl--;
  1791. } else break;
  1792. }
  1793. return returnDefinition ? {
  1794. "l": bl,
  1795. "def": positions[bl] ? positions[bl].match : undefined
  1796. } : bl;
  1797. }
  1798. function clearOptionalTail(buffer) {
  1799. var rl = determineLastRequiredPosition(),
  1800. lmib = buffer.length - 1;
  1801. for (; lmib > rl; lmib--) {
  1802. if (isMask(lmib)) break; //fixme ismask is not good enough
  1803. }
  1804. buffer.splice(rl, lmib + 1 - rl);
  1805. return buffer;
  1806. }
  1807. function isComplete(buffer) { //return true / false / undefined (repeat *)
  1808. if ($.isFunction(opts.isComplete)) return opts.isComplete(buffer, opts);
  1809. if (opts.repeat === "*") return undefined;
  1810. var complete = false,
  1811. lrp = determineLastRequiredPosition(true),
  1812. aml = seekPrevious(lrp.l);
  1813. if (lrp.def === undefined || lrp.def.newBlockMarker || lrp.def.optionality || lrp.def.optionalQuantifier) {
  1814. complete = true;
  1815. for (var i = 0; i <= aml; i++) {
  1816. var test = getTestTemplate(i).match;
  1817. if ((test.fn !== null && getMaskSet().validPositions[i] === undefined && test.optionality !== true && test.optionalQuantifier !== true) || (test.fn === null && buffer[i] !== getPlaceholder(i, test))) {
  1818. complete = false;
  1819. break;
  1820. }
  1821. }
  1822. }
  1823. return complete;
  1824. }
  1825. var EventRuler = {
  1826. on: function (input, eventName, eventHandler) {
  1827. var ev = function (e) {
  1828. // console.log("triggered " + e.type);
  1829. if (this.inputmask === undefined && this.nodeName !== "FORM") { //happens when cloning an object with jquery.clone
  1830. var imOpts = $.data(this, "_inputmask_opts");
  1831. if (imOpts)(new Inputmask(imOpts)).mask(this);
  1832. else EventRuler.off(this);
  1833. } else if (e.type !== "setvalue" && (this.disabled || (this.readOnly && !(e.type === "keydown" && (e.ctrlKey && e.keyCode === 67) || (opts.tabThrough === false && e.keyCode === Inputmask.keyCode.TAB))))) {
  1834. e.preventDefault();
  1835. } else {
  1836. switch (e.type) {
  1837. case "input":
  1838. if (skipInputEvent === true) {
  1839. skipInputEvent = false;
  1840. return e.preventDefault();
  1841. }
  1842. break;
  1843. case "keydown":
  1844. //Safari 5.1.x - modal dialog fires keypress twice workaround
  1845. skipKeyPressEvent = false;
  1846. skipInputEvent = false;
  1847. break;
  1848. case "keypress":
  1849. if (skipKeyPressEvent === true) {
  1850. return e.preventDefault();
  1851. }
  1852. skipKeyPressEvent = true;
  1853. break;
  1854. case "click":
  1855. if (iemobile || iphone) {
  1856. var that = this, args = arguments;
  1857. setTimeout(function () {
  1858. eventHandler.apply(that, args);
  1859. }, 0);
  1860. return false;
  1861. }
  1862. break;
  1863. }
  1864. // console.log("executed " + e.type);
  1865. var returnVal = eventHandler.apply(this, arguments);
  1866. if (returnVal === false) {
  1867. e.preventDefault();
  1868. e.stopPropagation();
  1869. }
  1870. return returnVal;
  1871. }
  1872. };
  1873. //keep instance of the event
  1874. input.inputmask.events[eventName] = input.inputmask.events[eventName] || [];
  1875. input.inputmask.events[eventName].push(ev);
  1876. if ($.inArray(eventName, ["submit", "reset"]) !== -1) {
  1877. if (input.form != null) $(input.form).on(eventName, ev);
  1878. } else {
  1879. $(input).on(eventName, ev);
  1880. }
  1881. },
  1882. off: function (input, event) {
  1883. if (input.inputmask && input.inputmask.events) {
  1884. var events;
  1885. if (event) {
  1886. events = [];
  1887. events[event] = input.inputmask.events[event];
  1888. } else {
  1889. events = input.inputmask.events;
  1890. }
  1891. $.each(events, function (eventName, evArr) {
  1892. while (evArr.length > 0) {
  1893. var ev = evArr.pop();
  1894. if ($.inArray(eventName, ["submit", "reset"]) !== -1) {
  1895. if (input.form != null) $(input.form).off(eventName, ev);
  1896. } else {
  1897. $(input).off(eventName, ev);
  1898. }
  1899. }
  1900. delete input.inputmask.events[eventName];
  1901. });
  1902. }
  1903. }
  1904. };
  1905. function patchValueProperty(npt) {
  1906. var valueGet;
  1907. var valueSet;
  1908. function patchValhook(type) {
  1909. if ($.valHooks && ($.valHooks[type] === undefined || $.valHooks[type].inputmaskpatch !== true)) {
  1910. var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) {
  1911. return elem.value;
  1912. };
  1913. var valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
  1914. elem.value = value;
  1915. return elem;
  1916. };
  1917. $.valHooks[type] = {
  1918. get: function (elem) {
  1919. if (elem.inputmask) {
  1920. if (elem.inputmask.opts.autoUnmask) {
  1921. return elem.inputmask.unmaskedvalue();
  1922. } else {
  1923. var result = valhookGet(elem);
  1924. return getLastValidPosition(undefined, undefined, elem.inputmask.maskset.validPositions) !== -1 || opts.nullable !== true ? result : "";
  1925. }
  1926. } else return valhookGet(elem);
  1927. },
  1928. set: function (elem, value) {
  1929. var $elem = $(elem),
  1930. result;
  1931. result = valhookSet(elem, value);
  1932. if (elem.inputmask) {
  1933. $elem.trigger("setvalue");
  1934. }
  1935. return result;
  1936. },
  1937. inputmaskpatch: true
  1938. };
  1939. }
  1940. }
  1941. function getter() {
  1942. if (this.inputmask) {
  1943. return this.inputmask.opts.autoUnmask ?
  1944. this.inputmask.unmaskedvalue() :
  1945. (getLastValidPosition() !== -1 || opts.nullable !== true ?
  1946. (document.activeElement === this && opts.clearMaskOnLostFocus ?
  1947. (isRTL ? clearOptionalTail(getBuffer().slice()).reverse() : clearOptionalTail(getBuffer().slice())).join("") :
  1948. valueGet.call(this)) :
  1949. "");
  1950. } else return valueGet.call(this);
  1951. }
  1952. function setter(value) {
  1953. valueSet.call(this, value);
  1954. if (this.inputmask) {
  1955. $(this).trigger("setvalue");
  1956. }
  1957. }
  1958. function installNativeValueSetFallback(npt) {
  1959. EventRuler.on(npt, "mouseenter", function (event) {
  1960. var $input = $(this),
  1961. input = this,
  1962. value = input.inputmask._valueGet();
  1963. if (value !== getBuffer().join("") /*&& getLastValidPosition() > 0*/) {
  1964. $input.trigger("setvalue");
  1965. }
  1966. });
  1967. }
  1968. if (!npt.inputmask.__valueGet) {
  1969. if (opts.noValuePatching !== true) {
  1970. if (Object.getOwnPropertyDescriptor) {
  1971. if (typeof Object.getPrototypeOf !== "function") {
  1972. Object.getPrototypeOf = typeof "test".__proto__ === "object" ? function (object) {
  1973. return object.__proto__;
  1974. } : function (object) {
  1975. return object.constructor.prototype;
  1976. };
  1977. }
  1978. var valueProperty = Object.getPrototypeOf ? Object.getOwnPropertyDescriptor(Object.getPrototypeOf(npt), "value") : undefined;
  1979. if (valueProperty && valueProperty.get && valueProperty.set) {
  1980. valueGet = valueProperty.get;
  1981. valueSet = valueProperty.set;
  1982. Object.defineProperty(npt, "value", {
  1983. get: getter,
  1984. set: setter,
  1985. configurable: true
  1986. });
  1987. } else if (npt.tagName !== "INPUT") {
  1988. valueGet = function () {
  1989. return this.textContent;
  1990. };
  1991. valueSet = function (value) {
  1992. this.textContent = value;
  1993. };
  1994. Object.defineProperty(npt, "value", {
  1995. get: getter,
  1996. set: setter,
  1997. configurable: true
  1998. });
  1999. }
  2000. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  2001. valueGet = npt.__lookupGetter__("value");
  2002. valueSet = npt.__lookupSetter__("value");
  2003. npt.__defineGetter__("value", getter);
  2004. npt.__defineSetter__("value", setter);
  2005. }
  2006. npt.inputmask.__valueGet = valueGet; //store native property getter
  2007. npt.inputmask.__valueSet = valueSet; //store native property setter
  2008. }
  2009. npt.inputmask._valueGet = function (overruleRTL) {
  2010. return isRTL && overruleRTL !== true ? valueGet.call(this.el).split("").reverse().join("") : valueGet.call(this.el);
  2011. };
  2012. npt.inputmask._valueSet = function (value, overruleRTL) { //null check is needed for IE8 => otherwise converts to "null"
  2013. valueSet.call(this.el, (value === null || value === undefined) ? "" : ((overruleRTL !== true && isRTL) ? value.split("").reverse().join("") : value));
  2014. };
  2015. if (valueGet === undefined) { //jquery.val fallback
  2016. valueGet = function () {
  2017. return this.value;
  2018. };
  2019. valueSet = function (value) {
  2020. this.value = value;
  2021. };
  2022. patchValhook(npt.type);
  2023. installNativeValueSetFallback(npt);
  2024. }
  2025. }
  2026. }
  2027. function handleRemove(input, k, pos, strict) {
  2028. function generalize() {
  2029. if (opts.keepStatic) {
  2030. var validInputs = [],
  2031. lastAlt = getLastValidPosition(-1, true), positionsClone = $.extend(true, {}, getMaskSet().validPositions),
  2032. prevAltPos = getMaskSet().validPositions[lastAlt];
  2033. //find last alternation
  2034. for (; lastAlt >= 0; lastAlt--) {
  2035. var altPos = getMaskSet().validPositions[lastAlt];
  2036. if (altPos) {
  2037. if (altPos.generatedInput !== true && /[0-9a-bA-Z]/.test(altPos.input)) {
  2038. validInputs.push(altPos.input);
  2039. }
  2040. delete getMaskSet().validPositions[lastAlt];
  2041. if (altPos.alternation !== undefined && altPos.locator[altPos.alternation] !== prevAltPos.locator[altPos.alternation]) {
  2042. break;
  2043. }
  2044. prevAltPos = altPos;
  2045. }
  2046. }
  2047. if (lastAlt > -1) {
  2048. getMaskSet().p = seekNext(getLastValidPosition(-1, true));
  2049. while (validInputs.length > 0) {
  2050. var keypress = new $.Event("keypress");
  2051. keypress.which = validInputs.pop().charCodeAt(0);
  2052. keypressEvent.call(input, keypress, true, false, false, getMaskSet().p);
  2053. }
  2054. } else getMaskSet().validPositions = $.extend(true, {}, positionsClone); //restore original positions
  2055. }
  2056. }
  2057. if (opts.numericInput || isRTL) {
  2058. if (k === Inputmask.keyCode.BACKSPACE) {
  2059. k = Inputmask.keyCode.DELETE;
  2060. } else if (k === Inputmask.keyCode.DELETE) {
  2061. k = Inputmask.keyCode.BACKSPACE;
  2062. }
  2063. if (isRTL) {
  2064. var pend = pos.end;
  2065. pos.end = pos.begin;
  2066. pos.begin = pend;
  2067. }
  2068. }
  2069. if (k === Inputmask.keyCode.BACKSPACE && (pos.end - pos.begin < 1 || opts.insertMode === false)) {
  2070. pos.begin = seekPrevious(pos.begin);
  2071. if (getMaskSet().validPositions[pos.begin] !== undefined && (getMaskSet().validPositions[pos.begin].input === opts.groupSeparator || getMaskSet().validPositions[pos.begin].input === opts.radixPoint)) {
  2072. pos.begin--;
  2073. }
  2074. } else if (k === Inputmask.keyCode.DELETE && pos.begin === pos.end) {
  2075. pos.end = isMask(pos.end, true) ? pos.end + 1 : seekNext(pos.end) + 1;
  2076. if (getMaskSet().validPositions[pos.begin] !== undefined && (getMaskSet().validPositions[pos.begin].input === opts.groupSeparator || getMaskSet().validPositions[pos.begin].input === opts.radixPoint)) {
  2077. pos.end++;
  2078. }
  2079. }
  2080. stripValidPositions(pos.begin, pos.end, false, strict);
  2081. if (strict !== true) {
  2082. generalize(); //revert the alternation
  2083. }
  2084. var lvp = getLastValidPosition(pos.begin, true);
  2085. if (lvp < pos.begin) {
  2086. //if (lvp === -1) resetMaskSet();
  2087. getMaskSet().p = seekNext(lvp);
  2088. } else if (strict !== true) {
  2089. getMaskSet().p = pos.begin;
  2090. }
  2091. }
  2092. function keydownEvent(e) {
  2093. function isInputEventSupported(eventName) {
  2094. var el = document.createElement("input"),
  2095. evName = "on" + eventName,
  2096. isSupported = (evName in el);
  2097. if (!isSupported) {
  2098. el.setAttribute(evName, "return;");
  2099. isSupported = typeof el[evName] == "function";
  2100. }
  2101. el = null;
  2102. return isSupported;
  2103. }
  2104. var input = this,
  2105. $input = $(input),
  2106. k = e.keyCode,
  2107. pos = caret(input);
  2108. //backspace, delete, and escape get special treatment
  2109. if (k === Inputmask.keyCode.BACKSPACE || k === Inputmask.keyCode.DELETE || (iphone && k === Inputmask.keyCode.BACKSPACE_SAFARI) || (e.ctrlKey && k === Inputmask.keyCode.X && !isInputEventSupported("cut"))) { //backspace/delete
  2110. e.preventDefault(); //stop default action but allow propagation
  2111. handleRemove(input, k, pos);
  2112. writeBuffer(input, getBuffer(true), getMaskSet().p, e, input.inputmask._valueGet() !== getBuffer().join(""));
  2113. if (input.inputmask._valueGet() === getBufferTemplate().join("")) {
  2114. $input.trigger("cleared");
  2115. } else if (isComplete(getBuffer()) === true) {
  2116. $input.trigger("complete");
  2117. }
  2118. if (opts.showTooltip) { //update tooltip
  2119. input.title = opts.tooltip || getMaskSet().mask;
  2120. }
  2121. } else if (k === Inputmask.keyCode.END || k === Inputmask.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  2122. e.preventDefault();
  2123. var caretPos = seekNext(getLastValidPosition());
  2124. if (!opts.insertMode && caretPos === getMaskSet().maskLength && !e.shiftKey) caretPos--;
  2125. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos, true);
  2126. } else if ((k === Inputmask.keyCode.HOME && !e.shiftKey) || k === Inputmask.keyCode.PAGE_UP) { //Home or page_up
  2127. e.preventDefault();
  2128. caret(input, 0, e.shiftKey ? pos.begin : 0, true);
  2129. } else if (((opts.undoOnEscape && k === Inputmask.keyCode.ESCAPE) || (k === 90 && e.ctrlKey)) && e.altKey !== true) { //escape && undo && #762
  2130. checkVal(input, true, false, undoValue.split(""));
  2131. $input.trigger("click");
  2132. } else if (k === Inputmask.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
  2133. opts.insertMode = !opts.insertMode;
  2134. caret(input, !opts.insertMode && pos.begin === getMaskSet().maskLength ? pos.begin - 1 : pos.begin);
  2135. } else if (opts.tabThrough === true && k === Inputmask.keyCode.TAB) {
  2136. if (e.shiftKey === true) {
  2137. if (getTest(pos.begin).match.fn === null) {
  2138. pos.begin = seekNext(pos.begin);
  2139. }
  2140. pos.end = seekPrevious(pos.begin, true);
  2141. pos.begin = seekPrevious(pos.end, true);
  2142. } else {
  2143. pos.begin = seekNext(pos.begin, true);
  2144. pos.end = seekNext(pos.begin, true);
  2145. if (pos.end < getMaskSet().maskLength) pos.end--;
  2146. }
  2147. if (pos.begin < getMaskSet().maskLength) {
  2148. e.preventDefault();
  2149. caret(input, pos.begin, pos.end);
  2150. }
  2151. } else if (!e.shiftKey) {
  2152. if (opts.insertMode === false) {
  2153. if (k === Inputmask.keyCode.RIGHT) {
  2154. setTimeout(function () {
  2155. var caretPos = caret(input);
  2156. caret(input, caretPos.begin);
  2157. }, 0);
  2158. } else if (k === Inputmask.keyCode.LEFT) {
  2159. setTimeout(function () {
  2160. var caretPos = caret(input);
  2161. caret(input, isRTL ? caretPos.begin + 1 : caretPos.begin - 1);
  2162. }, 0);
  2163. }
  2164. } else {
  2165. setTimeout(function () {
  2166. renderColorMask(input);
  2167. }, 0);
  2168. }
  2169. }
  2170. opts.onKeyDown.call(this, e, getBuffer(), caret(input).begin, opts);
  2171. ignorable = $.inArray(k, opts.ignorables) !== -1;
  2172. }
  2173. function keypressEvent(e, checkval, writeOut, strict, ndx) {
  2174. var input = this,
  2175. $input = $(input),
  2176. k = e.which || e.charCode || e.keyCode;
  2177. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  2178. if (k === Inputmask.keyCode.ENTER && undoValue !== getBuffer().join("")) {
  2179. undoValue = getBuffer().join("");
  2180. // e.preventDefault();
  2181. setTimeout(function () {
  2182. $input.trigger("change");
  2183. }, 0);
  2184. }
  2185. return true;
  2186. } else {
  2187. if (k) {
  2188. //special treat the decimal separator
  2189. if (k === 46 && e.shiftKey === false && opts.radixPoint === ",") k = 44;
  2190. var pos = checkval ? {
  2191. begin: ndx,
  2192. end: ndx
  2193. } : caret(input),
  2194. forwardPosition, c = String.fromCharCode(k);
  2195. getMaskSet().writeOutBuffer = true;
  2196. var valResult = isValid(pos, c, strict);
  2197. if (valResult !== false) {
  2198. resetMaskSet(true);
  2199. forwardPosition = valResult.caret !== undefined ? valResult.caret : checkval ? valResult.pos + 1 : seekNext(valResult.pos);
  2200. getMaskSet().p = forwardPosition; //needed for checkval
  2201. }
  2202. if (writeOut !== false) {
  2203. var self = this;
  2204. setTimeout(function () {
  2205. opts.onKeyValidation.call(self, k, valResult, opts);
  2206. }, 0);
  2207. if (getMaskSet().writeOutBuffer && valResult !== false) {
  2208. var buffer = getBuffer();
  2209. writeBuffer(input, buffer, (opts.numericInput && valResult.caret === undefined) ? seekPrevious(forwardPosition) : forwardPosition, e, checkval !== true);
  2210. if (checkval !== true) {
  2211. setTimeout(function () { //timeout needed for IE
  2212. if (isComplete(buffer) === true) $input.trigger("complete");
  2213. }, 0);
  2214. }
  2215. }
  2216. }
  2217. if (opts.showTooltip) { //update tooltip
  2218. input.title = opts.tooltip || getMaskSet().mask;
  2219. }
  2220. e.preventDefault();
  2221. if (checkval) {
  2222. valResult.forwardPosition = forwardPosition;
  2223. return valResult;
  2224. }
  2225. }
  2226. }
  2227. }
  2228. function pasteEvent(e) {
  2229. var input = this,
  2230. ev = e.originalEvent || e,
  2231. $input = $(input),
  2232. inputValue = input.inputmask._valueGet(true),
  2233. caretPos = caret(input),
  2234. tempValue;
  2235. if (isRTL) {
  2236. tempValue = caretPos.end;
  2237. caretPos.end = caretPos.begin;
  2238. caretPos.begin = tempValue;
  2239. }
  2240. var valueBeforeCaret = inputValue.substr(0, caretPos.begin),
  2241. valueAfterCaret = inputValue.substr(caretPos.end, inputValue.length);
  2242. if (valueBeforeCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(0, caretPos.begin).join("")) valueBeforeCaret = "";
  2243. if (valueAfterCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(caretPos.end).join("")) valueAfterCaret = "";
  2244. if (isRTL) {
  2245. tempValue = valueBeforeCaret;
  2246. valueBeforeCaret = valueAfterCaret;
  2247. valueAfterCaret = tempValue;
  2248. }
  2249. if (window.clipboardData && window.clipboardData.getData) { // IE
  2250. inputValue = valueBeforeCaret + window.clipboardData.getData("Text") + valueAfterCaret;
  2251. } else if (ev.clipboardData && ev.clipboardData.getData) {
  2252. inputValue = valueBeforeCaret + ev.clipboardData.getData("text/plain") + valueAfterCaret;
  2253. } else return true; //allow native paste event as fallback ~ masking will continue by inputfallback
  2254. var pasteValue = inputValue;
  2255. if ($.isFunction(opts.onBeforePaste)) {
  2256. pasteValue = opts.onBeforePaste(inputValue, opts);
  2257. if (pasteValue === false) {
  2258. return e.preventDefault();
  2259. }
  2260. if (!pasteValue) {
  2261. pasteValue = inputValue;
  2262. }
  2263. }
  2264. checkVal(input, false, false, isRTL ? pasteValue.split("").reverse() : pasteValue.toString().split(""));
  2265. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()), e, undoValue !== getBuffer().join(""));
  2266. if (isComplete(getBuffer()) === true) {
  2267. $input.trigger("complete");
  2268. }
  2269. return e.preventDefault();
  2270. }
  2271. function inputFallBackEvent(e) { //fallback when keypress fails
  2272. var input = this,
  2273. inputValue = input.inputmask._valueGet();
  2274. //console.log(inputValue);
  2275. if (getBuffer().join("") !== inputValue) {
  2276. var caretPos = caret(input);
  2277. inputValue = inputValue.replace(new RegExp("(" + Inputmask.escapeRegex(getBufferTemplate().join("")) + ")*"), "");
  2278. if (iemobile) { //iemobile just set the character at the end althought the caret position is correctly set
  2279. var inputChar = inputValue.replace(getBuffer().join(""), "");
  2280. if (inputChar.length === 1) {
  2281. var keypress = new $.Event("keypress");
  2282. keypress.which = inputChar.charCodeAt(0);
  2283. keypressEvent.call(input, keypress, true, true, false, getMaskSet().validPositions[caretPos.begin - 1] ? caretPos.begin : caretPos.begin - 1);
  2284. return false;
  2285. }
  2286. }
  2287. if (caretPos.begin > inputValue.length) {
  2288. caret(input, inputValue.length);
  2289. caretPos = caret(input);
  2290. }
  2291. //detect & treat possible backspace before static
  2292. if ((getBuffer().length - inputValue.length) === 1 && inputValue.charAt(caretPos.begin) !== getBuffer()[caretPos.begin] && inputValue.charAt(caretPos.begin + 1) !== getBuffer()[caretPos.begin] && !isMask(caretPos.begin)) {
  2293. e.keyCode = Inputmask.keyCode.BACKSPACE;
  2294. keydownEvent.call(input, e);
  2295. } else {
  2296. var lvp = getLastValidPosition() + 1;
  2297. var bufferTemplate = getBufferTemplate().join(""); //getBuffer().slice(lvp).join('');
  2298. while (inputValue.match(Inputmask.escapeRegex(bufferTemplate) + "$") === null) {
  2299. bufferTemplate = bufferTemplate.slice(1);
  2300. }
  2301. inputValue = inputValue.replace(bufferTemplate, "");
  2302. inputValue = inputValue.split("");
  2303. checkVal(input, true, false, inputValue, e, caretPos.begin < lvp);
  2304. if (isComplete(getBuffer()) === true) {
  2305. $(input).trigger("complete");
  2306. }
  2307. }
  2308. e.preventDefault();
  2309. }
  2310. }
  2311. function setValueEvent(e) {
  2312. var input = this,
  2313. value = input.inputmask._valueGet();
  2314. checkVal(input, true, false, ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(value, opts) || value) : value).split(""));
  2315. undoValue = getBuffer().join("");
  2316. if ((opts.clearMaskOnLostFocus || opts.clearIncomplete) && input.inputmask._valueGet() === getBufferTemplate().join("")) {
  2317. input.inputmask._valueSet("");
  2318. }
  2319. }
  2320. function focusEvent(e) {
  2321. var input = this,
  2322. nptValue = input.inputmask._valueGet();
  2323. if (opts.showMaskOnFocus && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue === ""))) {
  2324. if (input.inputmask._valueGet() !== getBuffer().join("")) {
  2325. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
  2326. } else if (mouseEnter === false) { //only executed on focus without mouseenter
  2327. caret(input, seekNext(getLastValidPosition()));
  2328. }
  2329. }
  2330. if (opts.positionCaretOnTab === true) {
  2331. setTimeout(function () {
  2332. clickEvent.apply(this, [e]);
  2333. }, 0);
  2334. }
  2335. undoValue = getBuffer().join("");
  2336. }
  2337. function mouseleaveEvent(e) {
  2338. var input = this;
  2339. mouseEnter = false;
  2340. if (opts.clearMaskOnLostFocus && document.activeElement !== input) {
  2341. var buffer = getBuffer().slice(),
  2342. nptValue = input.inputmask._valueGet();
  2343. if (nptValue !== input.getAttribute("placeholder") && nptValue !== "") {
  2344. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  2345. buffer = [];
  2346. } else { //clearout optional tail of the mask
  2347. clearOptionalTail(buffer);
  2348. }
  2349. writeBuffer(input, buffer);
  2350. }
  2351. }
  2352. }
  2353. function clickEvent(e) {
  2354. function doRadixFocus(clickPos) {
  2355. if (opts.radixPoint !== "") {
  2356. var vps = getMaskSet().validPositions;
  2357. if (vps[clickPos] === undefined || (vps[clickPos].input === getPlaceholder(clickPos))) {
  2358. if (clickPos < seekNext(-1)) return true;
  2359. var radixPos = $.inArray(opts.radixPoint, getBuffer());
  2360. if (radixPos !== -1) {
  2361. for (var vp in vps) {
  2362. if (radixPos < vp && vps[vp].input !== getPlaceholder(vp)) {
  2363. return false;
  2364. }
  2365. }
  2366. return true;
  2367. }
  2368. }
  2369. }
  2370. return false;
  2371. }
  2372. var input = this;
  2373. setTimeout(function () { //needed for Chrome ~ initial selection clears after the clickevent
  2374. if (document.activeElement === input) {
  2375. var selectedCaret = caret(input);
  2376. if (selectedCaret.begin === selectedCaret.end) {
  2377. switch (opts.positionCaretOnClick) {
  2378. case "none":
  2379. break;
  2380. case "radixFocus":
  2381. if (doRadixFocus(selectedCaret.begin)) {
  2382. var radixPos = $.inArray(opts.radixPoint, getBuffer().join(""));
  2383. caret(input, opts.numericInput ? seekNext(radixPos) : radixPos);
  2384. break;
  2385. }
  2386. default: //lvp:
  2387. var clickPosition = selectedCaret.begin,
  2388. lvclickPosition = getLastValidPosition(clickPosition, true),
  2389. lastPosition = seekNext(lvclickPosition);
  2390. if (clickPosition < lastPosition) {
  2391. caret(input, !isMask(clickPosition) && !isMask(clickPosition - 1) ? seekNext(clickPosition) : clickPosition);
  2392. } else {
  2393. var placeholder = getPlaceholder(lastPosition);
  2394. if ((placeholder !== "" && getBuffer()[lastPosition] !== placeholder && getTest(lastPosition).match.optionalQuantifier !== true) || (!isMask(lastPosition) && getTest(lastPosition).match.def === placeholder)) {
  2395. lastPosition = seekNext(lastPosition);
  2396. }
  2397. caret(input, lastPosition);
  2398. }
  2399. break;
  2400. }
  2401. }
  2402. }
  2403. }, 0);
  2404. }
  2405. function dblclickEvent(e) {
  2406. var input = this;
  2407. setTimeout(function () {
  2408. caret(input, 0, seekNext(getLastValidPosition()));
  2409. }, 0);
  2410. }
  2411. function cutEvent(e) {
  2412. var input = this,
  2413. $input = $(input),
  2414. pos = caret(input),
  2415. ev = e.originalEvent || e;
  2416. //correct clipboardData
  2417. var clipboardData = window.clipboardData || ev.clipboardData,
  2418. clipData = isRTL ? getBuffer().slice(pos.end, pos.begin) : getBuffer().slice(pos.begin, pos.end);
  2419. clipboardData.setData("text", isRTL ? clipData.reverse().join("") : clipData.join(""));
  2420. if (document.execCommand) document.execCommand("copy"); // copy selected content to system clipbaord
  2421. handleRemove(input, Inputmask.keyCode.DELETE, pos);
  2422. writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join(""));
  2423. if (input.inputmask._valueGet() === getBufferTemplate().join("")) {
  2424. $input.trigger("cleared");
  2425. }
  2426. if (opts.showTooltip) { //update tooltip
  2427. input.title = opts.tooltip || getMaskSet().mask;
  2428. }
  2429. }
  2430. function blurEvent(e) {
  2431. var $input = $(this),
  2432. input = this;
  2433. if (input.inputmask) {
  2434. var nptValue = input.inputmask._valueGet(),
  2435. buffer = getBuffer().slice();
  2436. if (undoValue !== buffer.join("")) {
  2437. setTimeout(function () { //change event should be triggered after the other buffer manipulations on blur
  2438. $input.trigger("change");
  2439. undoValue = buffer.join("");
  2440. }, 0);
  2441. }
  2442. if (nptValue !== "") {
  2443. if (opts.clearMaskOnLostFocus) {
  2444. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  2445. buffer = [];
  2446. } else { //clearout optional tail of the mask
  2447. clearOptionalTail(buffer);
  2448. }
  2449. }
  2450. if (isComplete(buffer) === false) {
  2451. setTimeout(function () {
  2452. $input.trigger("incomplete");
  2453. }, 0);
  2454. if (opts.clearIncomplete) {
  2455. resetMaskSet();
  2456. if (opts.clearMaskOnLostFocus) {
  2457. buffer = [];
  2458. } else {
  2459. buffer = getBufferTemplate().slice();
  2460. }
  2461. }
  2462. }
  2463. writeBuffer(input, buffer, undefined, e);
  2464. }
  2465. }
  2466. }
  2467. function mouseenterEvent(e) {
  2468. var input = this;
  2469. mouseEnter = true;
  2470. if (document.activeElement !== input && opts.showMaskOnHover) {
  2471. if (input.inputmask._valueGet() !== getBuffer().join("")) {
  2472. writeBuffer(input, getBuffer());
  2473. }
  2474. }
  2475. }
  2476. function submitEvent(e) { //trigger change on submit if any
  2477. if (undoValue !== getBuffer().join("")) {
  2478. $el.trigger("change");
  2479. }
  2480. if (opts.clearMaskOnLostFocus && getLastValidPosition() === -1 && el.inputmask._valueGet && el.inputmask._valueGet() === getBufferTemplate().join("")) {
  2481. el.inputmask._valueSet(""); //clear masktemplete on submit and still has focus
  2482. }
  2483. if (opts.removeMaskOnSubmit) {
  2484. el.inputmask._valueSet(el.inputmask.unmaskedvalue(), true);
  2485. setTimeout(function () {
  2486. writeBuffer(el, getBuffer());
  2487. }, 0);
  2488. }
  2489. }
  2490. function resetEvent(e) {
  2491. setTimeout(function () {
  2492. $el.trigger("setvalue");
  2493. }, 0);
  2494. }
  2495. function initializeColorMask(input) {
  2496. function findCaretPos(clientx) {
  2497. //calculate text width
  2498. var e = document.createElement('span'), caretPos;
  2499. for (var style in computedStyle) { //clone styles
  2500. if (isNaN(style) && style.indexOf("font") !== -1) {
  2501. e.style[style] = computedStyle[style];
  2502. }
  2503. }
  2504. e.style.textTransform = computedStyle.textTransform;
  2505. e.style.letterSpacing = computedStyle.letterSpacing;
  2506. e.style.position = "absolute";
  2507. e.style.height = "auto";
  2508. e.style.width = "auto";
  2509. e.style.visibility = "hidden";
  2510. e.style.whiteSpace = "nowrap";
  2511. document.body.appendChild(e);
  2512. var inputText = input.inputmask._valueGet(), previousWidth = 0, itl;
  2513. for (caretPos = 0, itl = inputText.length; caretPos <= itl; caretPos++) {
  2514. e.innerHTML += inputText.charAt(caretPos) || "_";
  2515. if (e.offsetWidth >= clientx) {
  2516. var offset1 = (clientx - previousWidth);
  2517. var offset2 = e.offsetWidth - clientx;
  2518. e.innerHTML = inputText.charAt(caretPos);
  2519. offset1 -= (e.offsetWidth / 3);
  2520. caretPos = offset1 < offset2 ? caretPos - 1 : caretPos;
  2521. break;
  2522. }
  2523. previousWidth = e.offsetWidth;
  2524. }
  2525. document.body.removeChild(e);
  2526. return caretPos;
  2527. }
  2528. function position() {
  2529. colorMask.style.position = "absolute";
  2530. colorMask.style.top = offset.top + "px";
  2531. colorMask.style.left = offset.left + "px";
  2532. colorMask.style.width = parseInt(input.offsetWidth) - parseInt(computedStyle.paddingLeft) - parseInt(computedStyle.paddingRight) - parseInt(computedStyle.borderLeftWidth) - parseInt(computedStyle.borderRightWidth) + "px";
  2533. colorMask.style.height = parseInt(input.offsetHeight) - parseInt(computedStyle.paddingTop) - parseInt(computedStyle.paddingBottom) - parseInt(computedStyle.borderTopWidth) - parseInt(computedStyle.borderBottomWidth) + "px";
  2534. colorMask.style.lineHeight = colorMask.style.height;
  2535. colorMask.style.zIndex = isNaN(computedStyle.zIndex) ? -1 : computedStyle.zIndex - 1;
  2536. colorMask.style.webkitAppearance = "textfield";
  2537. colorMask.style.mozAppearance = "textfield";
  2538. colorMask.style.Appearance = "textfield";
  2539. }
  2540. var offset = $(input).position(),
  2541. computedStyle = (input.ownerDocument.defaultView || window).getComputedStyle(input, null),
  2542. parentNode = input.parentNode;
  2543. colorMask = document.createElement("div");
  2544. document.body.appendChild(colorMask); //insert at body to prevent css clash :last-child for example
  2545. for (var style in computedStyle) { //clone styles
  2546. if (isNaN(style) && style !== "cssText" && style.indexOf("webkit") == -1) {
  2547. colorMask.style[style] = computedStyle[style];
  2548. }
  2549. }
  2550. //restyle input
  2551. input.style.backgroundColor = "transparent";
  2552. input.style.color = "transparent";
  2553. input.style.webkitAppearance = "caret";
  2554. input.style.mozAppearance = "caret";
  2555. input.style.Appearance = "caret";
  2556. position();
  2557. //event passthrough
  2558. $(window).on("resize", function (e) {
  2559. offset = $(input).position();
  2560. computedStyle = (input.ownerDocument.defaultView || window).getComputedStyle(input, null);
  2561. position();
  2562. });
  2563. $(input).on("click", function (e) {
  2564. caret(input, findCaretPos(e.clientX));
  2565. return clickEvent.call(this, [e]);
  2566. });
  2567. }
  2568. function renderColorMask(input, buffer, caretPos) {
  2569. function handleStatic() {
  2570. if (!static && (test.fn === null || testPos.input === undefined)) {
  2571. static = true;
  2572. maskTemplate += "<span class='im-static''>"
  2573. } else if (static && (test.fn !== null && testPos.input !== undefined)) {
  2574. static = false;
  2575. maskTemplate += "</span>"
  2576. }
  2577. }
  2578. if (colorMask !== undefined) {
  2579. buffer = buffer || getBuffer();
  2580. if (caretPos === undefined) {
  2581. caretPos = caret(input);
  2582. } else if (caretPos.begin === undefined) {
  2583. caretPos = {begin: caretPos, end: caretPos};
  2584. }
  2585. var maskTemplate = "", static = false;
  2586. if (buffer != "") {
  2587. var ndxIntlzr, pos = 0,
  2588. test, testPos, lvp = getLastValidPosition();
  2589. do {
  2590. if (pos === caretPos.begin && document.activeElement === input) {
  2591. maskTemplate += "<span class='im-caret' style='border-right-width: 1px;border-right-style: solid;'></span>";
  2592. }
  2593. if (getMaskSet().validPositions[pos]) {
  2594. testPos = getMaskSet().validPositions[pos];
  2595. test = testPos.match;
  2596. ndxIntlzr = testPos.locator.slice();
  2597. handleStatic();
  2598. maskTemplate += testPos.input;
  2599. } else {
  2600. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  2601. test = testPos.match;
  2602. ndxIntlzr = testPos.locator.slice();
  2603. if (opts.jitMasking === false || pos < lvp || (Number.isFinite(opts.jitMasking) && opts.jitMasking > pos)) {
  2604. handleStatic();
  2605. maskTemplate += getPlaceholder(pos, test);
  2606. }
  2607. }
  2608. pos++;
  2609. } while ((maxLength === undefined || pos < maxLength) && (test.fn !== null || test.def !== "") || lvp > pos);
  2610. }
  2611. colorMask.innerHTML = maskTemplate;
  2612. }
  2613. }
  2614. function mask(elem) {
  2615. function isElementTypeSupported(input, opts) {
  2616. var elementType = input.getAttribute("type");
  2617. var isSupported = (input.tagName === "INPUT" && $.inArray(elementType, opts.supportsInputType) !== -1) || input.isContentEditable || input.tagName === "TEXTAREA";
  2618. if (!isSupported && input.tagName === "INPUT") {
  2619. var el = document.createElement("input");
  2620. el.setAttribute("type", elementType);
  2621. isSupported = el.type === "text"; //apply mask only if the type is not natively supported
  2622. el = null;
  2623. }
  2624. return isSupported;
  2625. }
  2626. if (isElementTypeSupported(elem, opts)) {
  2627. el = elem;
  2628. $el = $(el);
  2629. //show tooltip
  2630. if (opts.showTooltip) {
  2631. el.title = opts.tooltip || getMaskSet().mask;
  2632. }
  2633. if (el.dir === "rtl" || opts.rightAlign) {
  2634. el.style.textAlign = "right";
  2635. }
  2636. if (el.dir === "rtl" || opts.numericInput) {
  2637. el.dir = "ltr";
  2638. el.removeAttribute("dir");
  2639. el.inputmask.isRTL = true;
  2640. isRTL = true;
  2641. }
  2642. if (opts.colorMask === true) {
  2643. initializeColorMask(el);
  2644. }
  2645. if (android) {
  2646. if (el.hasOwnProperty("inputmode")) {
  2647. el.inputmode = opts.inputmode;
  2648. el.setAttribute("inputmode", opts.inputmode);
  2649. }
  2650. if (opts.androidHack === "rtfm") {
  2651. if (opts.colorMask !== true) {
  2652. initializeColorMask(el);
  2653. }
  2654. el.type = "password";
  2655. }
  2656. }
  2657. //unbind all events - to make sure that no other mask will interfere when re-masking
  2658. EventRuler.off(el);
  2659. patchValueProperty(el);
  2660. //bind events
  2661. EventRuler.on(el, "submit", submitEvent);
  2662. EventRuler.on(el, "reset", resetEvent);
  2663. EventRuler.on(el, "mouseenter", mouseenterEvent);
  2664. EventRuler.on(el, "blur", blurEvent);
  2665. EventRuler.on(el, "focus", focusEvent);
  2666. EventRuler.on(el, "mouseleave", mouseleaveEvent);
  2667. if (opts.colorMask !== true)
  2668. EventRuler.on(el, "click", clickEvent);
  2669. EventRuler.on(el, "dblclick", dblclickEvent);
  2670. EventRuler.on(el, "paste", pasteEvent);
  2671. EventRuler.on(el, "dragdrop", pasteEvent);
  2672. EventRuler.on(el, "drop", pasteEvent);
  2673. EventRuler.on(el, "cut", cutEvent);
  2674. EventRuler.on(el, "complete", opts.oncomplete);
  2675. EventRuler.on(el, "incomplete", opts.onincomplete);
  2676. EventRuler.on(el, "cleared", opts.oncleared);
  2677. if (opts.inputEventOnly !== true) {
  2678. EventRuler.on(el, "keydown", keydownEvent);
  2679. EventRuler.on(el, "keypress", keypressEvent);
  2680. }
  2681. EventRuler.on(el, "compositionstart", $.noop);
  2682. EventRuler.on(el, "compositionupdate", $.noop);
  2683. EventRuler.on(el, "compositionend", $.noop);
  2684. EventRuler.on(el, "keyup", $.noop);
  2685. EventRuler.on(el, "input", inputFallBackEvent);
  2686. EventRuler.on(el, "setvalue", setValueEvent);
  2687. //apply mask
  2688. getBufferTemplate(); //initialize the buffer and getmasklength
  2689. if (el.inputmask._valueGet() !== "" || opts.clearMaskOnLostFocus === false || document.activeElement === el) {
  2690. var initialValue = $.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(el.inputmask._valueGet(), opts) || el.inputmask._valueGet()) : el.inputmask._valueGet();
  2691. checkVal(el, true, false, initialValue.split(""));
  2692. var buffer = getBuffer().slice();
  2693. undoValue = buffer.join("");
  2694. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  2695. if (isComplete(buffer) === false) {
  2696. if (opts.clearIncomplete) {
  2697. resetMaskSet();
  2698. }
  2699. }
  2700. if (opts.clearMaskOnLostFocus && document.activeElement !== el) {
  2701. if (getLastValidPosition() === -1) {
  2702. buffer = [];
  2703. } else {
  2704. clearOptionalTail(buffer);
  2705. }
  2706. }
  2707. writeBuffer(el, buffer);
  2708. if (document.activeElement === el) { //position the caret when in focus
  2709. caret(el, seekNext(getLastValidPosition()));
  2710. }
  2711. }
  2712. }
  2713. }
  2714. //action object
  2715. var valueBuffer;
  2716. if (actionObj !== undefined) {
  2717. switch (actionObj.action) {
  2718. case "isComplete":
  2719. el = actionObj.el;
  2720. return isComplete(getBuffer());
  2721. case "unmaskedvalue":
  2722. el = actionObj.el;
  2723. if (el !== undefined && el.inputmask !== undefined) {
  2724. maskset = el.inputmask.maskset;
  2725. opts = el.inputmask.opts;
  2726. isRTL = el.inputmask.isRTL;
  2727. } else {
  2728. valueBuffer = actionObj.value;
  2729. if (opts.numericInput) {
  2730. isRTL = true;
  2731. }
  2732. valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(valueBuffer, opts) || valueBuffer) : valueBuffer).split("");
  2733. checkVal(undefined, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  2734. if ($.isFunction(opts.onBeforeWrite)) opts.onBeforeWrite(undefined, getBuffer(), 0, opts);
  2735. }
  2736. return unmaskedvalue(el);
  2737. case "mask":
  2738. el = actionObj.el;
  2739. maskset = el.inputmask.maskset;
  2740. opts = el.inputmask.opts;
  2741. isRTL = el.inputmask.isRTL;
  2742. mask(el);
  2743. break;
  2744. case "format":
  2745. if (opts.numericInput) {
  2746. isRTL = true;
  2747. }
  2748. valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(actionObj.value, opts) || actionObj.value) : actionObj.value).split("");
  2749. checkVal(undefined, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  2750. if ($.isFunction(opts.onBeforeWrite)) opts.onBeforeWrite(undefined, getBuffer(), 0, opts);
  2751. if (actionObj.metadata) {
  2752. return {
  2753. value: isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join(""),
  2754. metadata: maskScope({
  2755. "action": "getmetadata"
  2756. }, maskset, opts)
  2757. };
  2758. }
  2759. return isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join("");
  2760. case "isValid":
  2761. if (opts.numericInput) {
  2762. isRTL = true;
  2763. }
  2764. if (actionObj.value) {
  2765. valueBuffer = actionObj.value.split("");
  2766. checkVal(undefined, false, true, isRTL ? valueBuffer.reverse() : valueBuffer);
  2767. } else {
  2768. actionObj.value = getBuffer().join("");
  2769. }
  2770. var buffer = getBuffer();
  2771. var rl = determineLastRequiredPosition(),
  2772. lmib = buffer.length - 1;
  2773. for (; lmib > rl; lmib--) {
  2774. if (isMask(lmib)) break;
  2775. }
  2776. buffer.splice(rl, lmib + 1 - rl);
  2777. return isComplete(buffer) && actionObj.value === getBuffer().join("");
  2778. case "getemptymask":
  2779. return getBufferTemplate().join("");
  2780. case "remove":
  2781. el = actionObj.el;
  2782. $el = $(el);
  2783. maskset = el.inputmask.maskset;
  2784. opts = el.inputmask.opts;
  2785. //writeout the unmaskedvalue
  2786. el.inputmask._valueSet(unmaskedvalue(el));
  2787. //unbind all events
  2788. EventRuler.off(el);
  2789. //restore the value property
  2790. var valueProperty;
  2791. if (Object.getOwnPropertyDescriptor && Object.getPrototypeOf) {
  2792. valueProperty = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el), "value");
  2793. if (valueProperty) {
  2794. if (el.inputmask.__valueGet) {
  2795. Object.defineProperty(el, "value", {
  2796. get: el.inputmask.__valueGet,
  2797. set: el.inputmask.__valueSet,
  2798. configurable: true
  2799. });
  2800. }
  2801. }
  2802. } else if (document.__lookupGetter__ && el.__lookupGetter__("value")) {
  2803. if (el.inputmask.__valueGet) {
  2804. el.__defineGetter__("value", el.inputmask.__valueGet);
  2805. el.__defineSetter__("value", el.inputmask.__valueSet);
  2806. }
  2807. }
  2808. //clear data
  2809. el.inputmask = undefined;
  2810. break;
  2811. case "getmetadata":
  2812. if ($.isArray(maskset.metadata)) {
  2813. var maskTarget = getMaskTemplate(true, 0, false).join("");
  2814. $.each(maskset.metadata, function (ndx, mtdt) {
  2815. if (mtdt.mask === maskTarget){
  2816. maskTarget = mtdt;
  2817. return false;
  2818. }
  2819. });
  2820. return maskTarget;
  2821. }
  2822. return maskset.metadata;
  2823. }
  2824. }
  2825. }
  2826. //make inputmask available
  2827. window.Inputmask = Inputmask;
  2828. return Inputmask;
  2829. }));