inputmask.js 115 KB

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