inputmask.js 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073
  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, 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: "[0-9A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]",
  131. cardinality: 1
  132. }
  133. },
  134. aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js
  135. masksCache: {},
  136. mask: function (elems) {
  137. var that = this;
  138. function importAttributeOptions(npt, opts, userOptions, dataAttribute) {
  139. var attrOptions = npt.getAttribute(dataAttribute),
  140. option, dataoptions, optionData, p;
  141. function importOption(option, optionData) {
  142. optionData = optionData !== undefined ? optionData : npt.getAttribute(dataAttribute + "-" + option);
  143. if (optionData !== null) {
  144. if (typeof optionData === "string") {
  145. if (option.indexOf("on") === 0) optionData = window[optionData]; //get function definition
  146. else if (optionData === "false") optionData = false;
  147. else if (optionData === "true") optionData = true;
  148. }
  149. userOptions[option] = optionData;
  150. }
  151. }
  152. if (attrOptions && attrOptions !== "") {
  153. attrOptions = attrOptions.replace(new RegExp("'", "g"), '"');
  154. dataoptions = JSON.parse("{" + attrOptions + "}");
  155. }
  156. //resolve aliases
  157. if (dataoptions) { //pickup alias from dataAttribute
  158. optionData = undefined;
  159. for (p in dataoptions) {
  160. if (p.toLowerCase() === "alias") {
  161. optionData = dataoptions[p];
  162. break;
  163. }
  164. }
  165. }
  166. importOption("alias", optionData); //pickup alias from dataAttribute-alias
  167. if (userOptions.alias) {
  168. resolveAlias(userOptions.alias, userOptions, opts);
  169. }
  170. for (option in opts) {
  171. if (dataoptions) {
  172. optionData = undefined;
  173. for (p in dataoptions) {
  174. if (p.toLowerCase() === option.toLowerCase()) {
  175. optionData = dataoptions[p];
  176. break;
  177. }
  178. }
  179. }
  180. importOption(option, optionData);
  181. }
  182. $.extend(true, opts, userOptions);
  183. return opts;
  184. }
  185. if (typeof elems === "string") {
  186. elems = document.getElementById(elems) || document.querySelectorAll(elems);
  187. }
  188. elems = elems.nodeName ? [elems] : elems;
  189. $.each(elems, function (ndx, el) {
  190. var scopedOpts = $.extend(true, {}, that.opts);
  191. importAttributeOptions(el, scopedOpts, $.extend(true, {}, that.userOptions), that.dataAttribute);
  192. var maskset = generateMaskSet(scopedOpts, that.noMasksCache);
  193. if (maskset !== undefined) {
  194. if (el.inputmask !== undefined) {
  195. el.inputmask.remove();
  196. }
  197. //store inputmask instance on the input with element reference
  198. el.inputmask = new Inputmask(undefined, undefined, true);
  199. el.inputmask.opts = scopedOpts;
  200. el.inputmask.noMasksCache = that.noMasksCache;
  201. el.inputmask.userOptions = $.extend(true, {}, that.userOptions);
  202. el.inputmask.isRTL = that.isRTL;
  203. el.inputmask.el = el;
  204. el.inputmask.maskset = maskset;
  205. $.data(el, "_inputmask_opts", scopedOpts);
  206. maskScope.call(el.inputmask, {
  207. "action": "mask"
  208. });
  209. }
  210. });
  211. return elems && elems[0] ? (elems[0].inputmask || this) : this;
  212. },
  213. option: function (options, noremask) { //set extra options || retrieve value of a current option
  214. if (typeof options === "string") {
  215. return this.opts[options];
  216. } else if (typeof options === "object") {
  217. $.extend(this.userOptions, options); //user passed options
  218. //remask
  219. if (this.el && noremask !== true) {
  220. this.mask(this.el);
  221. }
  222. return this;
  223. }
  224. },
  225. unmaskedvalue: function (value) {
  226. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  227. return maskScope.call(this, {
  228. "action": "unmaskedvalue",
  229. "value": value
  230. });
  231. },
  232. remove: function () {
  233. return maskScope.call(this, {
  234. "action": "remove"
  235. });
  236. },
  237. getemptymask: function () { //return the default (empty) mask value, usefull for setting the default value in validation
  238. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  239. return maskScope.call(this, {
  240. "action": "getemptymask"
  241. });
  242. },
  243. hasMaskedValue: function () { //check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value
  244. return !this.opts.autoUnmask;
  245. },
  246. isComplete: function () {
  247. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  248. return maskScope.call(this, {
  249. "action": "isComplete"
  250. });
  251. },
  252. getmetadata: function () { //return mask metadata if exists
  253. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  254. return maskScope.call(this, {
  255. "action": "getmetadata"
  256. });
  257. },
  258. isValid: function (value) {
  259. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  260. return maskScope.call(this, {
  261. "action": "isValid",
  262. "value": value
  263. });
  264. },
  265. format: function (value, metadata) {
  266. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  267. return maskScope.call(this, {
  268. "action": "format",
  269. "value": value,
  270. "metadata": metadata //true/false getmetadata
  271. });
  272. },
  273. analyseMask: function (mask, opts) {
  274. var tokenizer = /(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?\})|[^.?*+^${[]()|\\]+|./g,
  275. escaped = false,
  276. currentToken = new MaskToken(),
  277. match,
  278. m,
  279. openenings = [],
  280. maskTokens = [],
  281. openingToken,
  282. currentOpeningToken,
  283. alternator,
  284. lastMatch,
  285. groupToken;
  286. function MaskToken(isGroup, isOptional, isQuantifier, isAlternator) {
  287. this.matches = [];
  288. this.openGroup = isGroup || false;
  289. this.isGroup = isGroup || false;
  290. this.isOptional = isOptional || false;
  291. this.isQuantifier = isQuantifier || false;
  292. this.isAlternator = isAlternator || false;
  293. this.quantifier = {
  294. min: 1,
  295. max: 1
  296. };
  297. }
  298. //test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, casing: null/upper/lower, def: definitionSymbol, placeholder: placeholder, mask: real maskDefinition}
  299. function insertTestDefinition(mtoken, element, position) {
  300. var maskdef = (opts.definitions ? opts.definitions[element] : undefined) || Inputmask.prototype.definitions[element];
  301. position = position !== undefined ? position : mtoken.matches.length;
  302. var prevMatch = mtoken.matches[position - 1];
  303. if (maskdef && !escaped) {
  304. var prevalidators = maskdef.prevalidator,
  305. prevalidatorsL = prevalidators ? prevalidators.length : 0;
  306. //handle prevalidators
  307. for (var i = 1; i < maskdef.cardinality; i++) {
  308. var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [],
  309. validator = prevalidator.validator,
  310. cardinality = prevalidator.cardinality;
  311. mtoken.matches.splice(position++, 0, {
  312. fn: validator ? typeof validator === "string" ? new RegExp(validator) : new function () {
  313. this.test = validator;
  314. } : new RegExp("."),
  315. cardinality: cardinality ? cardinality : 1,
  316. optionality: mtoken.isOptional,
  317. newBlockMarker: prevMatch === undefined || prevMatch.def !== (maskdef.definitionSymbol || element),
  318. casing: maskdef.casing,
  319. def: maskdef.definitionSymbol || element,
  320. placeholder: maskdef.placeholder,
  321. nativeDef: element
  322. });
  323. prevMatch = mtoken.matches[position - 1];
  324. }
  325. mtoken.matches.splice(position++, 0, {
  326. fn: maskdef.validator ? typeof maskdef.validator == "string" ? new RegExp(maskdef.validator) : new function () {
  327. this.test = maskdef.validator;
  328. } : new RegExp("."),
  329. cardinality: maskdef.cardinality,
  330. optionality: mtoken.isOptional,
  331. newBlockMarker: prevMatch === undefined || prevMatch.def !== (maskdef.definitionSymbol || element),
  332. casing: maskdef.casing,
  333. def: maskdef.definitionSymbol || element,
  334. placeholder: maskdef.placeholder,
  335. nativeDef: element
  336. });
  337. } else {
  338. mtoken.matches.splice(position++, 0, {
  339. fn: null,
  340. cardinality: 0,
  341. optionality: mtoken.isOptional,
  342. newBlockMarker: prevMatch === undefined || prevMatch.def !== element,
  343. casing: null,
  344. def: opts.staticDefinitionSymbol || element,
  345. placeholder: opts.staticDefinitionSymbol !== undefined ? element : undefined,
  346. nativeDef: element
  347. });
  348. escaped = false;
  349. }
  350. }
  351. function verifyGroupMarker(maskToken) {
  352. if (maskToken && maskToken.matches) {
  353. $.each(maskToken.matches, function (ndx, token) {
  354. var nextToken = maskToken.matches[ndx + 1];
  355. if ((nextToken === undefined || (nextToken.matches === undefined || nextToken.isQuantifier === false)) && token && token.isGroup) { //this is not a group but a normal mask => convert
  356. token.isGroup = false;
  357. insertTestDefinition(token, opts.groupmarker.start, 0);
  358. if (token.openGroup !== true) {
  359. insertTestDefinition(token, opts.groupmarker.end);
  360. }
  361. }
  362. verifyGroupMarker(token);
  363. }
  364. );
  365. }
  366. }
  367. function defaultCase() {
  368. if (openenings.length > 0) {
  369. currentOpeningToken = openenings[openenings.length - 1];
  370. insertTestDefinition(currentOpeningToken, m);
  371. if (currentOpeningToken.isAlternator) { //handle alternator a | b case
  372. alternator = openenings.pop();
  373. for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
  374. alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group
  375. }
  376. if (openenings.length > 0) {
  377. currentOpeningToken = openenings[openenings.length - 1];
  378. currentOpeningToken.matches.push(alternator);
  379. } else {
  380. currentToken.matches.push(alternator);
  381. }
  382. }
  383. } else {
  384. insertTestDefinition(currentToken, m);
  385. }
  386. }
  387. function reverseTokens(maskToken) {
  388. function reverseStatic(st) {
  389. if (st === opts.optionalmarker.start) st = opts.optionalmarker.end;
  390. else if (st === opts.optionalmarker.end) st = opts.optionalmarker.start;
  391. else if (st === opts.groupmarker.start) st = opts.groupmarker.end;
  392. else if (st === opts.groupmarker.end) st = opts.groupmarker.start;
  393. return st;
  394. }
  395. maskToken.matches = maskToken.matches.reverse();
  396. for (var match in maskToken.matches) {
  397. if (maskToken.matches.hasOwnProperty(match)) {
  398. var intMatch = parseInt(match);
  399. if (maskToken.matches[match].isQuantifier && maskToken.matches[intMatch + 1] && maskToken.matches[intMatch + 1].isGroup) { //reposition quantifier
  400. var qt = maskToken.matches[match];
  401. maskToken.matches.splice(match, 1);
  402. maskToken.matches.splice(intMatch + 1, 0, qt);
  403. }
  404. if (maskToken.matches[match].matches !== undefined) {
  405. maskToken.matches[match] = reverseTokens(maskToken.matches[match]);
  406. } else {
  407. maskToken.matches[match] = reverseStatic(maskToken.matches[match]);
  408. }
  409. }
  410. }
  411. return maskToken;
  412. }
  413. while (match = tokenizer.exec(mask)) {
  414. m = match[0];
  415. if (escaped) {
  416. defaultCase();
  417. continue;
  418. }
  419. switch (m.charAt(0)) {
  420. case opts.escapeChar:
  421. escaped = true;
  422. break;
  423. case opts.optionalmarker.end:
  424. // optional closing
  425. case opts.groupmarker.end:
  426. // Group closing
  427. openingToken = openenings.pop();
  428. openingToken.openGroup = false; //mark group as complete
  429. if (openingToken !== undefined) {
  430. if (openenings.length > 0) {
  431. currentOpeningToken = openenings[openenings.length - 1];
  432. currentOpeningToken.matches.push(openingToken);
  433. if (currentOpeningToken.isAlternator) { //handle alternator (a) | (b) case
  434. alternator = openenings.pop();
  435. for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
  436. alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group
  437. }
  438. if (openenings.length > 0) {
  439. currentOpeningToken = openenings[openenings.length - 1];
  440. currentOpeningToken.matches.push(alternator);
  441. } else {
  442. currentToken.matches.push(alternator);
  443. }
  444. }
  445. } else {
  446. currentToken.matches.push(openingToken);
  447. }
  448. } else defaultCase();
  449. break;
  450. case opts.optionalmarker.start:
  451. // optional opening
  452. openenings.push(new MaskToken(false, true));
  453. break;
  454. case opts.groupmarker.start:
  455. // Group opening
  456. openenings.push(new MaskToken(true));
  457. break;
  458. case opts.quantifiermarker.start:
  459. //Quantifier
  460. var quantifier = new MaskToken(false, false, true);
  461. m = m.replace(/[{}]/g, "");
  462. var mq = m.split(","),
  463. mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]),
  464. mq1 = mq.length === 1 ? mq0 : (isNaN(mq[1]) ? mq[1] : parseInt(mq[1]));
  465. if (mq1 === "*" || mq1 === "+") {
  466. mq0 = mq1 === "*" ? 0 : 1;
  467. }
  468. quantifier.quantifier = {
  469. min: mq0,
  470. max: mq1
  471. };
  472. if (openenings.length > 0) {
  473. var matches = openenings[openenings.length - 1].matches;
  474. match = matches.pop();
  475. if (!match.isGroup) {
  476. groupToken = new MaskToken(true);
  477. groupToken.matches.push(match);
  478. match = groupToken;
  479. }
  480. matches.push(match);
  481. matches.push(quantifier);
  482. } else {
  483. match = currentToken.matches.pop();
  484. if (!match.isGroup) {
  485. groupToken = new MaskToken(true);
  486. groupToken.matches.push(match);
  487. match = groupToken;
  488. }
  489. currentToken.matches.push(match);
  490. currentToken.matches.push(quantifier);
  491. }
  492. break;
  493. case
  494. opts.alternatormarker:
  495. if (openenings.length > 0) {
  496. currentOpeningToken = openenings[openenings.length - 1];
  497. lastMatch = currentOpeningToken.matches.pop();
  498. } else {
  499. lastMatch = currentToken.matches.pop();
  500. }
  501. if (lastMatch.isAlternator) {
  502. openenings.push(lastMatch);
  503. } else {
  504. alternator = new MaskToken(false, false, false, true);
  505. alternator.matches.push(lastMatch);
  506. openenings.push(alternator);
  507. }
  508. break;
  509. default:
  510. defaultCase();
  511. }
  512. }
  513. while (openenings.length > 0) {
  514. openingToken = openenings.pop();
  515. currentToken.matches.push(openingToken);
  516. }
  517. if (currentToken.matches.length > 0) {
  518. verifyGroupMarker(currentToken);
  519. maskTokens.push(currentToken);
  520. }
  521. if (opts.numericInput) {
  522. reverseTokens(maskTokens[0]);
  523. }
  524. // console.log(JSON.stringify(maskTokens));
  525. return maskTokens;
  526. }
  527. };
  528. //apply defaults, definitions, aliases
  529. Inputmask.extendDefaults = function (options) {
  530. $.extend(true, Inputmask.prototype.defaults, options);
  531. };
  532. Inputmask.extendDefinitions = function (definition) {
  533. $.extend(true, Inputmask.prototype.definitions, definition);
  534. };
  535. Inputmask.extendAliases = function (alias) {
  536. $.extend(true, Inputmask.prototype.aliases, alias);
  537. };
  538. //static fn on inputmask
  539. Inputmask.format = function (value, options, metadata) {
  540. return Inputmask(options).format(value, metadata);
  541. };
  542. Inputmask.unmask = function (value, options) {
  543. return Inputmask(options).unmaskedvalue(value);
  544. };
  545. Inputmask.isValid = function (value, options) {
  546. return Inputmask(options).isValid(value);
  547. };
  548. Inputmask.remove = function (elems) {
  549. $.each(elems, function (ndx, el) {
  550. if (el.inputmask) el.inputmask.remove();
  551. });
  552. };
  553. Inputmask.escapeRegex = function (str) {
  554. var specials = ["/", ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\", "$", "^"];
  555. return str.replace(new RegExp("(\\" + specials.join("|\\") + ")", "gim"), "\\$1");
  556. };
  557. Inputmask.keyCode = {
  558. ALT: 18,
  559. BACKSPACE: 8,
  560. BACKSPACE_SAFARI: 127,
  561. CAPS_LOCK: 20,
  562. COMMA: 188,
  563. COMMAND: 91,
  564. COMMAND_LEFT: 91,
  565. COMMAND_RIGHT: 93,
  566. CONTROL: 17,
  567. DELETE: 46,
  568. DOWN: 40,
  569. END: 35,
  570. ENTER: 13,
  571. ESCAPE: 27,
  572. HOME: 36,
  573. INSERT: 45,
  574. LEFT: 37,
  575. MENU: 93,
  576. NUMPAD_ADD: 107,
  577. NUMPAD_DECIMAL: 110,
  578. NUMPAD_DIVIDE: 111,
  579. NUMPAD_ENTER: 108,
  580. NUMPAD_MULTIPLY: 106,
  581. NUMPAD_SUBTRACT: 109,
  582. PAGE_DOWN: 34,
  583. PAGE_UP: 33,
  584. PERIOD: 190,
  585. RIGHT: 39,
  586. SHIFT: 16,
  587. SPACE: 32,
  588. TAB: 9,
  589. UP: 38,
  590. WINDOWS: 91,
  591. X: 88
  592. };
  593. function resolveAlias(aliasStr, options, opts) {
  594. var aliasDefinition = Inputmask.prototype.aliases[aliasStr];
  595. if (aliasDefinition) {
  596. if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias, undefined, opts); //alias is another alias
  597. $.extend(true, opts, aliasDefinition); //merge alias definition in the options
  598. $.extend(true, opts, options); //reapply extra given options
  599. return true;
  600. } else //alias not found - try as mask
  601. if (opts.mask === null) {
  602. opts.mask = aliasStr;
  603. }
  604. return false;
  605. }
  606. function generateMaskSet(opts, nocache) {
  607. function generateMask(mask, metadata, opts) {
  608. if (mask === null || mask === "") {
  609. return undefined;
  610. } else {
  611. if (mask.length === 1 && opts.greedy === false && opts.repeat !== 0) {
  612. opts.placeholder = "";
  613. } //hide placeholder with single non-greedy mask
  614. if (opts.repeat > 0 || opts.repeat === "*" || opts.repeat === "+") {
  615. var repeatStart = opts.repeat === "*" ? 0 : (opts.repeat === "+" ? 1 : opts.repeat);
  616. mask = opts.groupmarker.start + mask + opts.groupmarker.end + opts.quantifiermarker.start + repeatStart + "," + opts.repeat + opts.quantifiermarker.end;
  617. }
  618. // console.log(mask);
  619. var masksetDefinition;
  620. if (Inputmask.prototype.masksCache[mask] === undefined || nocache === true) {
  621. masksetDefinition = {
  622. "mask": mask,
  623. "maskToken": Inputmask.prototype.analyseMask(mask, opts),
  624. "validPositions": {},
  625. "_buffer": undefined,
  626. "buffer": undefined,
  627. "tests": {},
  628. "metadata": metadata,
  629. maskLength: undefined
  630. };
  631. if (nocache !== true) {
  632. Inputmask.prototype.masksCache[opts.numericInput ? mask.split("").reverse().join("") : mask] = masksetDefinition;
  633. masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[opts.numericInput ? mask.split("").reverse().join("") : mask]);
  634. }
  635. } else masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[opts.numericInput ? mask.split("").reverse().join("") : mask]);
  636. return masksetDefinition;
  637. }
  638. }
  639. var ms;
  640. if ($.isFunction(opts.mask)) { //allow mask to be a preprocessing fn - should return a valid mask
  641. opts.mask = opts.mask(opts);
  642. }
  643. if ($.isArray(opts.mask)) {
  644. if (opts.mask.length > 1) {
  645. opts.keepStatic = opts.keepStatic === null ? true : opts.keepStatic; //enable by default when passing multiple masks when the option is not explicitly specified
  646. var altMask = opts.groupmarker.start;
  647. $.each(opts.numericInput ? opts.mask.reverse() : opts.mask, function (ndx, msk) {
  648. if (altMask.length > 1) {
  649. altMask += opts.groupmarker.end + opts.alternatormarker + opts.groupmarker.start;
  650. }
  651. if (msk.mask !== undefined && !$.isFunction(msk.mask)) {
  652. altMask += msk.mask;
  653. } else {
  654. altMask += msk;
  655. }
  656. });
  657. altMask += opts.groupmarker.end;
  658. // console.log(altMask);
  659. return generateMask(altMask, opts.mask, opts);
  660. } else opts.mask = opts.mask.pop();
  661. }
  662. if (opts.mask) {
  663. if (opts.mask.mask !== undefined && !$.isFunction(opts.mask.mask)) {
  664. ms = generateMask(opts.mask.mask, opts.mask, opts);
  665. } else {
  666. ms = generateMask(opts.mask, opts.mask, opts);
  667. }
  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.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 && opts.insertMode) :
  1201. (posObj.end - posObj.begin) > 1 || ((posObj.end - posObj.begin) === 1 && opts.insertMode);
  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(), pos.begin, c, 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;
  1559. if (strict) {
  1560. test = getTestTemplate(pos).match;
  1561. if (test.def === "") test = getTest(pos).match;
  1562. } else test = getTest(pos).match;
  1563. if (test.fn != null) {
  1564. return test.fn;
  1565. } else if (strict !== true && pos > -1) {
  1566. var tests = getTests(pos);
  1567. return tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0);
  1568. }
  1569. return false;
  1570. }
  1571. function seekNext(pos, newBlock) {
  1572. var maskL = getMaskSet().maskLength;
  1573. if (pos >= maskL) return maskL;
  1574. var position = pos;
  1575. while (++position < maskL &&
  1576. ((newBlock === true && (getTest(position).match.newBlockMarker !== true || !isMask(position))) ||
  1577. (newBlock !== true && !isMask(position)))) {
  1578. }
  1579. return position;
  1580. }
  1581. function seekPrevious(pos, newBlock) {
  1582. var position = pos, tests;
  1583. if (position <= 0) return 0;
  1584. while (--position > 0 &&
  1585. ((newBlock === true && getTest(position).match.newBlockMarker !== true) ||
  1586. (newBlock !== true && !isMask(position) &&
  1587. (tests = getTests(position), tests.length < 2 || (tests.length === 2 && tests[1].match.def === ""))))) {
  1588. }
  1589. return position;
  1590. }
  1591. function getBufferElement(position) {
  1592. return getMaskSet().validPositions[position] === undefined ? getPlaceholder(position) : getMaskSet().validPositions[position].input;
  1593. }
  1594. function writeBuffer(input, buffer, caretPos, event, triggerInputEvent) {
  1595. if (event && $.isFunction(opts.onBeforeWrite)) {
  1596. var result = opts.onBeforeWrite(event, buffer, caretPos, opts);
  1597. if (result) {
  1598. if (result.refreshFromBuffer) {
  1599. var refresh = result.refreshFromBuffer;
  1600. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer || buffer);
  1601. buffer = getBuffer(true);
  1602. }
  1603. //only alter when intented !== undefined
  1604. if (caretPos !== undefined) caretPos = result.caret !== undefined ? result.caret : caretPos;
  1605. }
  1606. }
  1607. input.inputmask._valueSet(buffer.join(""));
  1608. if (caretPos !== undefined && (event === undefined || event.type !== "blur")) {
  1609. if (android && event.type === "input") {
  1610. setTimeout(function () {
  1611. caret(input, caretPos);
  1612. }, 0);
  1613. } else caret(input, caretPos);
  1614. } else renderColorMask(input, buffer, caretPos);
  1615. if (triggerInputEvent === true) {
  1616. skipInputEvent = true;
  1617. $(input).trigger("input");
  1618. }
  1619. }
  1620. function getPlaceholder(pos, test, returnPL) {
  1621. test = test || getTest(pos).match;
  1622. if (test.placeholder !== undefined || returnPL === true) {
  1623. return $.isFunction(test.placeholder) ? test.placeholder(opts) : test.placeholder;
  1624. } else if (test.fn === null) {
  1625. if (pos > -1 && getMaskSet().validPositions[pos] === undefined) {
  1626. var tests = getTests(pos),
  1627. staticAlternations = [],
  1628. prevTest;
  1629. if (tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0)) {
  1630. for (var i = 0; i < tests.length; i++) {
  1631. if (tests[i].match.optionality !== true && tests[i].match.optionalQuantifier !== true &&
  1632. (tests[i].match.fn === null || (prevTest === undefined || tests[i].match.fn.test(prevTest.match.def, getMaskSet(), pos, true, opts) !== false))) {
  1633. staticAlternations.push(tests[i]);
  1634. if (tests[i].match.fn === null) prevTest = tests[i];
  1635. if (staticAlternations.length > 1) {
  1636. if (/[0-9a-bA-Z]/.test(staticAlternations[0].match.def)) {
  1637. return opts.placeholder.charAt(pos % opts.placeholder.length);
  1638. }
  1639. }
  1640. }
  1641. }
  1642. }
  1643. }
  1644. return test.def;
  1645. }
  1646. return opts.placeholder.charAt(pos % opts.placeholder.length);
  1647. }
  1648. function checkVal(input, writeOut, strict, nptvl, initiatingEvent, stickyCaret) {
  1649. var inputValue = nptvl.slice(),
  1650. charCodes = "",
  1651. initialNdx = 0, result = undefined;
  1652. function isTemplateMatch() {
  1653. var isMatch = false;
  1654. var charCodeNdx = getBufferTemplate().slice(initialNdx, seekNext(initialNdx)).join("").indexOf(charCodes);
  1655. if (charCodeNdx !== -1 && !isMask(initialNdx)) {
  1656. isMatch = true;
  1657. var bufferTemplateArr = getBufferTemplate().slice(initialNdx, initialNdx + charCodeNdx);
  1658. for (var i = 0; i < bufferTemplateArr.length; i++) {
  1659. if (bufferTemplateArr[i] !== " ") {
  1660. isMatch = false;
  1661. break;
  1662. }
  1663. }
  1664. }
  1665. return isMatch;
  1666. }
  1667. resetMaskSet();
  1668. getMaskSet().p = seekNext(-1);
  1669. // if (writeOut) input.inputmask._valueSet(""); //initial clear
  1670. if (!strict) {
  1671. if (opts.autoUnmask !== true) {
  1672. var staticInput = getBufferTemplate().slice(0, seekNext(-1)).join(""),
  1673. matches = inputValue.join("").match(new RegExp("^" + Inputmask.escapeRegex(staticInput), "g"));
  1674. if (matches && matches.length > 0) {
  1675. inputValue.splice(0, matches.length * staticInput.length);
  1676. initialNdx = seekNext(initialNdx);
  1677. }
  1678. } else {
  1679. initialNdx = seekNext(initialNdx);
  1680. }
  1681. }
  1682. $.each(inputValue, function (ndx, charCode) {
  1683. if (charCode !== undefined) { //inputfallback strips some elements out of the inputarray. $.each logically presents them as undefined
  1684. var keypress = new $.Event("_checkval");
  1685. keypress.which = charCode.charCodeAt(0);
  1686. charCodes += charCode;
  1687. var lvp = getLastValidPosition(undefined, true),
  1688. lvTest = getMaskSet().validPositions[lvp],
  1689. nextTest = getTestTemplate(lvp + 1, lvTest ? lvTest.locator.slice() : undefined, lvp);
  1690. if (!isTemplateMatch() || strict || opts.autoUnmask) {
  1691. var pos = strict ? ndx : (nextTest.match.fn == null && nextTest.match.optionality && (lvp + 1) < getMaskSet().p ? lvp + 1 : getMaskSet().p);
  1692. result = EventHandlers.keypressEvent.call(input, keypress, true, false, strict, pos);
  1693. initialNdx = pos + 1;
  1694. charCodes = "";
  1695. } else {
  1696. result = EventHandlers.keypressEvent.call(input, keypress, true, false, true, lvp + 1);
  1697. }
  1698. if (!strict && $.isFunction(opts.onBeforeWrite)) {
  1699. result = opts.onBeforeWrite(keypress, getBuffer(), result.forwardPosition, opts);
  1700. if (result && result.refreshFromBuffer) {
  1701. var refresh = result.refreshFromBuffer;
  1702. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer);
  1703. resetMaskSet(true);
  1704. if (result.caret) {
  1705. getMaskSet().p = result.caret;
  1706. }
  1707. }
  1708. }
  1709. }
  1710. });
  1711. if (writeOut) {
  1712. var caretPos = undefined, lvp = getLastValidPosition();
  1713. if (document.activeElement === input && (initiatingEvent || result)) {
  1714. caretPos = caret(input).begin;
  1715. if (initiatingEvent && result === false) caretPos = seekNext(getLastValidPosition(caretPos));
  1716. if (result && stickyCaret !== true && (caretPos < lvp + 1 || lvp === -1))
  1717. caretPos = (opts.numericInput && result.caret === undefined) ? seekPrevious(result.forwardPosition) : result.forwardPosition;
  1718. }
  1719. writeBuffer(input, getBuffer(), caretPos, initiatingEvent || new $.Event("checkval"));
  1720. }
  1721. }
  1722. function unmaskedvalue(input) {
  1723. if (input) {
  1724. if (input.inputmask === undefined) {
  1725. return input.value;
  1726. }
  1727. if (input.inputmask && input.inputmask.refreshValue) { //forced refresh from the value form.reset
  1728. EventHandlers.setValueEvent.call(input);
  1729. }
  1730. }
  1731. var umValue = [],
  1732. vps = getMaskSet().validPositions;
  1733. for (var pndx in vps) {
  1734. if (vps[pndx].match && vps[pndx].match.fn != null) {
  1735. umValue.push(vps[pndx].input);
  1736. }
  1737. }
  1738. var unmaskedValue = umValue.length === 0 ? "" : (isRTL ? umValue.reverse() : umValue).join("");
  1739. if ($.isFunction(opts.onUnMask)) {
  1740. var bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join("");
  1741. unmaskedValue = opts.onUnMask(bufferValue, unmaskedValue, opts);
  1742. }
  1743. return unmaskedValue;
  1744. }
  1745. function caret(input, begin, end, notranslate) {
  1746. function translatePosition(pos) {
  1747. if (notranslate !== true && isRTL && typeof pos === "number" && (!opts.greedy || opts.placeholder !== "")) {
  1748. 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)
  1749. pos = bffrLght - pos;
  1750. }
  1751. return pos;
  1752. }
  1753. var range;
  1754. if (typeof begin === "number") {
  1755. begin = translatePosition(begin);
  1756. end = translatePosition(end);
  1757. end = (typeof end == "number") ? end : begin;
  1758. // if (!$(input).is(":visible")) {
  1759. // return;
  1760. // }
  1761. var scrollCalc = parseInt(((input.ownerDocument.defaultView || window).getComputedStyle ? (input.ownerDocument.defaultView || window).getComputedStyle(input, null) : input.currentStyle).fontSize) * end;
  1762. input.scrollLeft = scrollCalc > input.scrollWidth ? scrollCalc : 0;
  1763. if (!mobile && opts.insertMode === false && begin === end) end++; //set visualization for insert/overwrite mode
  1764. if (input.setSelectionRange) {
  1765. input.selectionStart = begin;
  1766. input.selectionEnd = end;
  1767. } else if (window.getSelection) {
  1768. range = document.createRange();
  1769. if (input.firstChild === undefined || input.firstChild === null) {
  1770. var textNode = document.createTextNode("");
  1771. input.appendChild(textNode);
  1772. }
  1773. range.setStart(input.firstChild, begin < input.inputmask._valueGet().length ? begin : input.inputmask._valueGet().length);
  1774. range.setEnd(input.firstChild, end < input.inputmask._valueGet().length ? end : input.inputmask._valueGet().length);
  1775. range.collapse(true);
  1776. var sel = window.getSelection();
  1777. sel.removeAllRanges();
  1778. sel.addRange(range);
  1779. //input.focus();
  1780. } else if (input.createTextRange) {
  1781. range = input.createTextRange();
  1782. range.collapse(true);
  1783. range.moveEnd("character", end);
  1784. range.moveStart("character", begin);
  1785. range.select();
  1786. }
  1787. renderColorMask(input, undefined, {begin: begin, end: end});
  1788. } else {
  1789. if (input.setSelectionRange) {
  1790. begin = input.selectionStart;
  1791. end = input.selectionEnd;
  1792. } else if (window.getSelection) {
  1793. range = window.getSelection().getRangeAt(0);
  1794. if (range.commonAncestorContainer.parentNode === input || range.commonAncestorContainer === input) {
  1795. begin = range.startOffset;
  1796. end = range.endOffset;
  1797. }
  1798. } else if (document.selection && document.selection.createRange) {
  1799. range = document.selection.createRange();
  1800. begin = 0 - range.duplicate().moveStart("character", -input.inputmask._valueGet().length);
  1801. end = begin + range.text.length;
  1802. }
  1803. /*eslint-disable consistent-return */
  1804. return {
  1805. "begin": translatePosition(begin),
  1806. "end": translatePosition(end)
  1807. };
  1808. /*eslint-enable consistent-return */
  1809. }
  1810. }
  1811. function determineLastRequiredPosition(returnDefinition) {
  1812. var buffer = getBuffer(),
  1813. bl = buffer.length,
  1814. pos, lvp = getLastValidPosition(),
  1815. positions = {},
  1816. lvTest = getMaskSet().validPositions[lvp],
  1817. ndxIntlzr = lvTest !== undefined ? lvTest.locator.slice() : undefined,
  1818. testPos;
  1819. for (pos = lvp + 1; pos < buffer.length; pos++) {
  1820. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  1821. ndxIntlzr = testPos.locator.slice();
  1822. positions[pos] = $.extend(true, {}, testPos);
  1823. }
  1824. var lvTestAlt = lvTest && lvTest.alternation !== undefined ? lvTest.locator[lvTest.alternation] : undefined;
  1825. for (pos = bl - 1; pos > lvp; pos--) {
  1826. testPos = positions[pos];
  1827. if ((testPos.match.optionality ||
  1828. testPos.match.optionalQuantifier ||
  1829. (lvTestAlt &&
  1830. ((lvTestAlt !== positions[pos].locator[lvTest.alternation] && testPos.match.fn != null) ||
  1831. (testPos.match.fn === null && testPos.locator[lvTest.alternation] && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAlt.toString().split(",")) && getTests(pos)[0].def !== "")))) &&
  1832. buffer[pos] === getPlaceholder(pos, testPos.match)) {
  1833. bl--;
  1834. } else break;
  1835. }
  1836. return returnDefinition ? {
  1837. "l": bl,
  1838. "def": positions[bl] ? positions[bl].match : undefined
  1839. } : bl;
  1840. }
  1841. function clearOptionalTail(buffer) {
  1842. var rl = determineLastRequiredPosition(),
  1843. validPos, bl = buffer.length;
  1844. while (rl < bl && !isMask(rl + 1) && (validPos = getTest(rl + 1)) && validPos.match.optionality !== true && validPos.match.optionalQuantifier !== true) {
  1845. rl++;
  1846. }
  1847. while ((validPos = getTest(rl - 1)) && validPos.match.optionality && validPos.input === opts.skipOptionalPartCharacter) {
  1848. rl--;
  1849. }
  1850. buffer.splice(rl);
  1851. return buffer;
  1852. }
  1853. function isComplete(buffer) { //return true / false / undefined (repeat *)
  1854. if ($.isFunction(opts.isComplete)) return opts.isComplete(buffer, opts);
  1855. if (opts.repeat === "*") return undefined;
  1856. var complete = false,
  1857. lrp = determineLastRequiredPosition(true),
  1858. aml = seekPrevious(lrp.l);
  1859. if (lrp.def === undefined || lrp.def.newBlockMarker || lrp.def.optionality || lrp.def.optionalQuantifier) {
  1860. complete = true;
  1861. for (var i = 0; i <= aml; i++) {
  1862. var test = getTestTemplate(i).match;
  1863. if ((test.fn !== null && getMaskSet().validPositions[i] === undefined && test.optionality !== true && test.optionalQuantifier !== true) || (test.fn === null && buffer[i] !== getPlaceholder(i, test))) {
  1864. complete = false;
  1865. break;
  1866. }
  1867. }
  1868. }
  1869. return complete;
  1870. }
  1871. function handleRemove(input, k, pos, strict) {
  1872. function generalize() {
  1873. if (opts.keepStatic) {
  1874. var validInputs = [],
  1875. lastAlt = getLastValidPosition(-1, true), positionsClone = $.extend(true, {}, getMaskSet().validPositions),
  1876. prevAltPos = getMaskSet().validPositions[lastAlt];
  1877. //find last alternation
  1878. for (; lastAlt >= 0; lastAlt--) {
  1879. var altPos = getMaskSet().validPositions[lastAlt];
  1880. if (altPos) {
  1881. if (altPos.generatedInput !== true && /[0-9a-bA-Z]/.test(altPos.input)) {
  1882. validInputs.push(altPos.input);
  1883. }
  1884. delete getMaskSet().validPositions[lastAlt];
  1885. if (altPos.alternation !== undefined && altPos.locator[altPos.alternation] !== prevAltPos.locator[altPos.alternation]) {
  1886. break;
  1887. }
  1888. prevAltPos = altPos;
  1889. }
  1890. }
  1891. if (lastAlt > -1) {
  1892. getMaskSet().p = seekNext(getLastValidPosition(-1, true));
  1893. while (validInputs.length > 0) {
  1894. var keypress = new $.Event("keypress");
  1895. keypress.which = validInputs.pop().charCodeAt(0);
  1896. EventHandlers.keypressEvent.call(input, keypress, true, false, false, getMaskSet().p);
  1897. }
  1898. } else getMaskSet().validPositions = $.extend(true, {}, positionsClone); //restore original positions
  1899. }
  1900. }
  1901. if (opts.numericInput || isRTL) {
  1902. if (k === Inputmask.keyCode.BACKSPACE) {
  1903. k = Inputmask.keyCode.DELETE;
  1904. } else if (k === Inputmask.keyCode.DELETE) {
  1905. k = Inputmask.keyCode.BACKSPACE;
  1906. }
  1907. if (isRTL) {
  1908. var pend = pos.end;
  1909. pos.end = pos.begin;
  1910. pos.begin = pend;
  1911. }
  1912. }
  1913. if (k === Inputmask.keyCode.BACKSPACE && (pos.end - pos.begin < 1 || opts.insertMode === false)) {
  1914. pos.begin = seekPrevious(pos.begin);
  1915. if (getMaskSet().validPositions[pos.begin] !== undefined && (getMaskSet().validPositions[pos.begin].input === opts.groupSeparator || getMaskSet().validPositions[pos.begin].input === opts.radixPoint)) {
  1916. pos.begin--;
  1917. }
  1918. } else if (k === Inputmask.keyCode.DELETE && pos.begin === pos.end) {
  1919. pos.end = isMask(pos.end, true) ? pos.end + 1 : seekNext(pos.end) + 1;
  1920. if (getMaskSet().validPositions[pos.begin] !== undefined && (getMaskSet().validPositions[pos.begin].input === opts.groupSeparator || getMaskSet().validPositions[pos.begin].input === opts.radixPoint)) {
  1921. pos.end++;
  1922. }
  1923. }
  1924. stripValidPositions(pos.begin, pos.end, false, strict);
  1925. if (strict !== true) {
  1926. generalize(); //revert the alternation
  1927. }
  1928. var lvp = getLastValidPosition(pos.begin, true);
  1929. if (lvp < pos.begin) {
  1930. //if (lvp === -1) resetMaskSet();
  1931. getMaskSet().p = seekNext(lvp);
  1932. } else if (strict !== true) {
  1933. getMaskSet().p = pos.begin;
  1934. }
  1935. }
  1936. var EventRuler = {
  1937. on: function (input, eventName, eventHandler) {
  1938. var ev = function (e) {
  1939. // console.log("triggered " + e.type);
  1940. if (this.inputmask === undefined && this.nodeName !== "FORM") { //happens when cloning an object with jquery.clone
  1941. var imOpts = $.data(this, "_inputmask_opts");
  1942. if (imOpts) (new Inputmask(imOpts)).mask(this);
  1943. else EventRuler.off(this);
  1944. } 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))))) {
  1945. e.preventDefault();
  1946. } else {
  1947. switch (e.type) {
  1948. case "input":
  1949. if (skipInputEvent === true) {
  1950. skipInputEvent = false;
  1951. return e.preventDefault();
  1952. }
  1953. break;
  1954. case "keydown":
  1955. //Safari 5.1.x - modal dialog fires keypress twice workaround
  1956. skipKeyPressEvent = false;
  1957. skipInputEvent = false;
  1958. break;
  1959. case "keypress":
  1960. if (skipKeyPressEvent === true) {
  1961. return e.preventDefault();
  1962. }
  1963. skipKeyPressEvent = true;
  1964. break;
  1965. case "click":
  1966. if (iemobile || iphone) {
  1967. var that = this, args = arguments;
  1968. setTimeout(function () {
  1969. eventHandler.apply(that, args);
  1970. }, 0);
  1971. return false;
  1972. }
  1973. break;
  1974. }
  1975. // console.log("executed " + e.type);
  1976. var returnVal = eventHandler.apply(this, arguments);
  1977. if (returnVal === false) {
  1978. e.preventDefault();
  1979. e.stopPropagation();
  1980. }
  1981. return returnVal;
  1982. }
  1983. };
  1984. //keep instance of the event
  1985. input.inputmask.events[eventName] = input.inputmask.events[eventName] || [];
  1986. input.inputmask.events[eventName].push(ev);
  1987. if ($.inArray(eventName, ["submit", "reset"]) !== -1) {
  1988. if (input.form != null) $(input.form).on(eventName, ev);
  1989. } else {
  1990. $(input).on(eventName, ev);
  1991. }
  1992. },
  1993. off: function (input, event) {
  1994. if (input.inputmask && input.inputmask.events) {
  1995. var events;
  1996. if (event) {
  1997. events = [];
  1998. events[event] = input.inputmask.events[event];
  1999. } else {
  2000. events = input.inputmask.events;
  2001. }
  2002. $.each(events, function (eventName, evArr) {
  2003. while (evArr.length > 0) {
  2004. var ev = evArr.pop();
  2005. if ($.inArray(eventName, ["submit", "reset"]) !== -1) {
  2006. if (input.form != null) $(input.form).off(eventName, ev);
  2007. } else {
  2008. $(input).off(eventName, ev);
  2009. }
  2010. }
  2011. delete input.inputmask.events[eventName];
  2012. });
  2013. }
  2014. }
  2015. };
  2016. var EventHandlers = {
  2017. keydownEvent: function (e) {
  2018. function isInputEventSupported(eventName) {
  2019. var el = document.createElement("input"),
  2020. evName = "on" + eventName,
  2021. isSupported = (evName in el);
  2022. if (!isSupported) {
  2023. el.setAttribute(evName, "return;");
  2024. isSupported = typeof el[evName] == "function";
  2025. }
  2026. el = null;
  2027. return isSupported;
  2028. }
  2029. var input = this,
  2030. $input = $(input),
  2031. k = e.keyCode,
  2032. pos = caret(input);
  2033. //backspace, delete, and escape get special treatment
  2034. 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
  2035. e.preventDefault(); //stop default action but allow propagation
  2036. handleRemove(input, k, pos);
  2037. writeBuffer(input, getBuffer(true), getMaskSet().p, e, input.inputmask._valueGet() !== getBuffer().join(""));
  2038. if (input.inputmask._valueGet() === getBufferTemplate().join("")) {
  2039. $input.trigger("cleared");
  2040. } else if (isComplete(getBuffer()) === true) {
  2041. $input.trigger("complete");
  2042. }
  2043. } else if (k === Inputmask.keyCode.END || k === Inputmask.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  2044. e.preventDefault();
  2045. var caretPos = seekNext(getLastValidPosition());
  2046. if (!opts.insertMode && caretPos === getMaskSet().maskLength && !e.shiftKey) caretPos--;
  2047. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos, true);
  2048. } else if ((k === Inputmask.keyCode.HOME && !e.shiftKey) || k === Inputmask.keyCode.PAGE_UP) { //Home or page_up
  2049. e.preventDefault();
  2050. caret(input, 0, e.shiftKey ? pos.begin : 0, true);
  2051. } else if (((opts.undoOnEscape && k === Inputmask.keyCode.ESCAPE) || (k === 90 && e.ctrlKey)) && e.altKey !== true) { //escape && undo && #762
  2052. checkVal(input, true, false, undoValue.split(""));
  2053. $input.trigger("click");
  2054. } else if (k === Inputmask.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
  2055. opts.insertMode = !opts.insertMode;
  2056. caret(input, !opts.insertMode && pos.begin === getMaskSet().maskLength ? pos.begin - 1 : pos.begin);
  2057. } else if (opts.tabThrough === true && k === Inputmask.keyCode.TAB) {
  2058. if (e.shiftKey === true) {
  2059. if (getTest(pos.begin).match.fn === null) {
  2060. pos.begin = seekNext(pos.begin);
  2061. }
  2062. pos.end = seekPrevious(pos.begin, true);
  2063. pos.begin = seekPrevious(pos.end, true);
  2064. } else {
  2065. pos.begin = seekNext(pos.begin, true);
  2066. pos.end = seekNext(pos.begin, true);
  2067. if (pos.end < getMaskSet().maskLength) pos.end--;
  2068. }
  2069. if (pos.begin < getMaskSet().maskLength) {
  2070. e.preventDefault();
  2071. caret(input, pos.begin, pos.end);
  2072. }
  2073. } else if (!e.shiftKey) {
  2074. if (opts.insertMode === false) {
  2075. if (k === Inputmask.keyCode.RIGHT) {
  2076. setTimeout(function () {
  2077. var caretPos = caret(input);
  2078. caret(input, caretPos.begin);
  2079. }, 0);
  2080. } else if (k === Inputmask.keyCode.LEFT) {
  2081. setTimeout(function () {
  2082. var caretPos = caret(input);
  2083. caret(input, isRTL ? caretPos.begin + 1 : caretPos.begin - 1);
  2084. }, 0);
  2085. }
  2086. }
  2087. }
  2088. opts.onKeyDown.call(this, e, getBuffer(), caret(input).begin, opts);
  2089. ignorable = $.inArray(k, opts.ignorables) !== -1;
  2090. },
  2091. keypressEvent: function (e, checkval, writeOut, strict, ndx) {
  2092. var input = this,
  2093. $input = $(input),
  2094. k = e.which || e.charCode || e.keyCode;
  2095. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  2096. if (k === Inputmask.keyCode.ENTER && undoValue !== getBuffer().join("")) {
  2097. undoValue = getBuffer().join("");
  2098. // e.preventDefault();
  2099. setTimeout(function () {
  2100. $input.trigger("change");
  2101. }, 0);
  2102. }
  2103. return true;
  2104. } else {
  2105. if (k) {
  2106. //special treat the decimal separator
  2107. if (k === 46 && e.shiftKey === false && opts.radixPoint !== "") k = opts.radixPoint.charCodeAt(0);
  2108. var pos = checkval ? {
  2109. begin: ndx,
  2110. end: ndx
  2111. } : caret(input),
  2112. forwardPosition, c = String.fromCharCode(k);
  2113. getMaskSet().writeOutBuffer = true;
  2114. var valResult = isValid(pos, c, strict);
  2115. if (valResult !== false) {
  2116. resetMaskSet(true);
  2117. forwardPosition = valResult.caret !== undefined ? valResult.caret : checkval ? valResult.pos + 1 : seekNext(valResult.pos);
  2118. getMaskSet().p = forwardPosition; //needed for checkval
  2119. }
  2120. if (writeOut !== false) {
  2121. var self = this;
  2122. setTimeout(function () {
  2123. opts.onKeyValidation.call(self, k, valResult, opts);
  2124. }, 0);
  2125. if (getMaskSet().writeOutBuffer && valResult !== false) {
  2126. var buffer = getBuffer();
  2127. writeBuffer(input, buffer, (opts.numericInput && valResult.caret === undefined) ? seekPrevious(forwardPosition) : forwardPosition, e, checkval !== true);
  2128. if (checkval !== true) {
  2129. setTimeout(function () { //timeout needed for IE
  2130. if (isComplete(buffer) === true) $input.trigger("complete");
  2131. }, 0);
  2132. }
  2133. }
  2134. }
  2135. e.preventDefault();
  2136. if (checkval) {
  2137. valResult.forwardPosition = forwardPosition;
  2138. return valResult;
  2139. }
  2140. }
  2141. }
  2142. },
  2143. pasteEvent: function (e) {
  2144. var input = this,
  2145. ev = e.originalEvent || e,
  2146. $input = $(input),
  2147. inputValue = input.inputmask._valueGet(true),
  2148. caretPos = caret(input),
  2149. tempValue;
  2150. if (isRTL) {
  2151. tempValue = caretPos.end;
  2152. caretPos.end = caretPos.begin;
  2153. caretPos.begin = tempValue;
  2154. }
  2155. var valueBeforeCaret = inputValue.substr(0, caretPos.begin),
  2156. valueAfterCaret = inputValue.substr(caretPos.end, inputValue.length);
  2157. if (valueBeforeCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(0, caretPos.begin).join("")) valueBeforeCaret = "";
  2158. if (valueAfterCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(caretPos.end).join("")) valueAfterCaret = "";
  2159. if (isRTL) {
  2160. tempValue = valueBeforeCaret;
  2161. valueBeforeCaret = valueAfterCaret;
  2162. valueAfterCaret = tempValue;
  2163. }
  2164. if (window.clipboardData && window.clipboardData.getData) { // IE
  2165. inputValue = valueBeforeCaret + window.clipboardData.getData("Text") + valueAfterCaret;
  2166. } else if (ev.clipboardData && ev.clipboardData.getData) {
  2167. inputValue = valueBeforeCaret + ev.clipboardData.getData("text/plain") + valueAfterCaret;
  2168. } else return true; //allow native paste event as fallback ~ masking will continue by inputfallback
  2169. var pasteValue = inputValue;
  2170. if ($.isFunction(opts.onBeforePaste)) {
  2171. pasteValue = opts.onBeforePaste(inputValue, opts);
  2172. if (pasteValue === false) {
  2173. return e.preventDefault();
  2174. }
  2175. if (!pasteValue) {
  2176. pasteValue = inputValue;
  2177. }
  2178. }
  2179. checkVal(input, false, false, isRTL ? pasteValue.split("").reverse() : pasteValue.toString().split(""));
  2180. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()), e, undoValue !== getBuffer().join(""));
  2181. if (isComplete(getBuffer()) === true) {
  2182. $input.trigger("complete");
  2183. }
  2184. return e.preventDefault();
  2185. },
  2186. inputFallBackEvent: function (e) { //fallback when keypress fails
  2187. var input = this,
  2188. inputValue = input.inputmask._valueGet();
  2189. //console.log(inputValue);
  2190. if (getBuffer().join("") !== inputValue) {
  2191. var caretPos = caret(input);
  2192. inputValue = inputValue.replace(new RegExp("(" + Inputmask.escapeRegex(getBufferTemplate().join("")) + ")*"), "");
  2193. if (iemobile) { //iemobile just set the character at the end althought the caret position is correctly set
  2194. var inputChar = inputValue.replace(getBuffer().join(""), "");
  2195. if (inputChar.length === 1) {
  2196. var keypress = new $.Event("keypress");
  2197. keypress.which = inputChar.charCodeAt(0);
  2198. EventHandlers.keypressEvent.call(input, keypress, true, true, false, getMaskSet().validPositions[caretPos.begin - 1] ? caretPos.begin : caretPos.begin - 1);
  2199. return false;
  2200. }
  2201. }
  2202. if (caretPos.begin > inputValue.length) {
  2203. caret(input, inputValue.length);
  2204. caretPos = caret(input);
  2205. }
  2206. //detect & treat possible backspace before static
  2207. if ((getBuffer().length - inputValue.length) === 1 && inputValue.charAt(caretPos.begin) !== getBuffer()[caretPos.begin] && inputValue.charAt(caretPos.begin + 1) !== getBuffer()[caretPos.begin] && !isMask(caretPos.begin)) {
  2208. e.keyCode = Inputmask.keyCode.BACKSPACE;
  2209. EventHandlers.keydownEvent.call(input, e);
  2210. } else {
  2211. var lvp = getLastValidPosition() + 1;
  2212. var bufferTemplate = getBufferTemplate().join(""); //getBuffer().slice(lvp).join('');
  2213. while (inputValue.match(Inputmask.escapeRegex(bufferTemplate) + "$") === null) {
  2214. bufferTemplate = bufferTemplate.slice(1);
  2215. }
  2216. inputValue = inputValue.replace(bufferTemplate, "");
  2217. inputValue = inputValue.split("");
  2218. checkVal(input, true, false, inputValue, e, caretPos.begin < lvp);
  2219. if (isComplete(getBuffer()) === true) {
  2220. $(input).trigger("complete");
  2221. }
  2222. }
  2223. e.preventDefault();
  2224. }
  2225. },
  2226. setValueEvent: function (e) {
  2227. this.inputmask.refreshValue = false;
  2228. var input = this,
  2229. value = input.inputmask._valueGet();
  2230. checkVal(input, true, false, ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(value, opts) || value) : value).split(""));
  2231. undoValue = getBuffer().join("");
  2232. if ((opts.clearMaskOnLostFocus || opts.clearIncomplete) && input.inputmask._valueGet() === getBufferTemplate().join("")) {
  2233. input.inputmask._valueSet("");
  2234. }
  2235. },
  2236. focusEvent: function (e) {
  2237. var input = this,
  2238. nptValue = input.inputmask._valueGet();
  2239. if (opts.showMaskOnFocus && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue === ""))) {
  2240. if (input.inputmask._valueGet() !== getBuffer().join("")) {
  2241. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
  2242. } else if (mouseEnter === false) { //only executed on focus without mouseenter
  2243. caret(input, seekNext(getLastValidPosition()));
  2244. }
  2245. }
  2246. if (opts.positionCaretOnTab === true) {
  2247. EventHandlers.clickEvent.apply(input, [e, true]);
  2248. }
  2249. undoValue = getBuffer().join("");
  2250. },
  2251. mouseleaveEvent: function (e) {
  2252. var input = this;
  2253. mouseEnter = false;
  2254. if (opts.clearMaskOnLostFocus && document.activeElement !== input) {
  2255. var buffer = getBuffer().slice(),
  2256. nptValue = input.inputmask._valueGet();
  2257. if (nptValue !== input.getAttribute("placeholder") && nptValue !== "") {
  2258. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  2259. buffer = [];
  2260. } else { //clearout optional tail of the mask
  2261. clearOptionalTail(buffer);
  2262. }
  2263. writeBuffer(input, buffer);
  2264. }
  2265. }
  2266. },
  2267. clickEvent: function (e, tabbed) {
  2268. function doRadixFocus(clickPos) {
  2269. if (opts.radixPoint !== "") {
  2270. var vps = getMaskSet().validPositions;
  2271. if (vps[clickPos] === undefined || (vps[clickPos].input === getPlaceholder(clickPos))) {
  2272. if (clickPos < seekNext(-1)) return true;
  2273. var radixPos = $.inArray(opts.radixPoint, getBuffer());
  2274. if (radixPos !== -1) {
  2275. for (var vp in vps) {
  2276. if (radixPos < vp && vps[vp].input !== getPlaceholder(vp)) {
  2277. return false;
  2278. }
  2279. }
  2280. return true;
  2281. }
  2282. }
  2283. }
  2284. return false;
  2285. }
  2286. var input = this;
  2287. setTimeout(function () { //needed for Chrome ~ initial selection clears after the clickevent
  2288. if (document.activeElement === input) {
  2289. var selectedCaret = caret(input);
  2290. if (tabbed) selectedCaret.begin = selectedCaret.end;
  2291. if (selectedCaret.begin === selectedCaret.end) {
  2292. switch (opts.positionCaretOnClick) {
  2293. case "none":
  2294. break;
  2295. case "radixFocus":
  2296. if (doRadixFocus(selectedCaret.begin)) {
  2297. var radixPos = $.inArray(opts.radixPoint, getBuffer().join(""));
  2298. caret(input, opts.numericInput ? seekNext(radixPos) : radixPos);
  2299. break;
  2300. }
  2301. default: //lvp:
  2302. var clickPosition = selectedCaret.begin,
  2303. lvclickPosition = getLastValidPosition(clickPosition, true),
  2304. lastPosition = seekNext(lvclickPosition);
  2305. if (clickPosition < lastPosition) {
  2306. caret(input, !isMask(clickPosition) && !isMask(clickPosition - 1) ? seekNext(clickPosition) : clickPosition);
  2307. } else {
  2308. var placeholder = getPlaceholder(lastPosition);
  2309. if ((placeholder !== "" && getBuffer()[lastPosition] !== placeholder && getTest(lastPosition).match.optionalQuantifier !== true) || (!isMask(lastPosition) && getTest(lastPosition).match.def === placeholder)) {
  2310. lastPosition = seekNext(lastPosition);
  2311. }
  2312. caret(input, lastPosition);
  2313. }
  2314. break;
  2315. }
  2316. }
  2317. }
  2318. }, 0);
  2319. },
  2320. dblclickEvent: function (e) {
  2321. var input = this;
  2322. setTimeout(function () {
  2323. caret(input, 0, seekNext(getLastValidPosition()));
  2324. }, 0);
  2325. },
  2326. cutEvent: function (e) {
  2327. var input = this,
  2328. $input = $(input),
  2329. pos = caret(input),
  2330. ev = e.originalEvent || e;
  2331. //correct clipboardData
  2332. var clipboardData = window.clipboardData || ev.clipboardData,
  2333. clipData = isRTL ? getBuffer().slice(pos.end, pos.begin) : getBuffer().slice(pos.begin, pos.end);
  2334. clipboardData.setData("text", isRTL ? clipData.reverse().join("") : clipData.join(""));
  2335. if (document.execCommand) document.execCommand("copy"); // copy selected content to system clipbaord
  2336. handleRemove(input, Inputmask.keyCode.DELETE, pos);
  2337. writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join(""));
  2338. if (input.inputmask._valueGet() === getBufferTemplate().join("")) {
  2339. $input.trigger("cleared");
  2340. }
  2341. },
  2342. blurEvent: function (e) {
  2343. var $input = $(this),
  2344. input = this;
  2345. if (input.inputmask) {
  2346. var nptValue = input.inputmask._valueGet(),
  2347. buffer = getBuffer().slice();
  2348. if (undoValue !== buffer.join("")) {
  2349. setTimeout(function () { //change event should be triggered after the other buffer manipulations on blur
  2350. $input.trigger("change");
  2351. undoValue = buffer.join("");
  2352. }, 0);
  2353. }
  2354. if (nptValue !== "") {
  2355. if (opts.clearMaskOnLostFocus) {
  2356. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  2357. buffer = [];
  2358. } else { //clearout optional tail of the mask
  2359. clearOptionalTail(buffer);
  2360. }
  2361. }
  2362. if (isComplete(buffer) === false) {
  2363. setTimeout(function () {
  2364. $input.trigger("incomplete");
  2365. }, 0);
  2366. if (opts.clearIncomplete) {
  2367. resetMaskSet();
  2368. if (opts.clearMaskOnLostFocus) {
  2369. buffer = [];
  2370. } else {
  2371. buffer = getBufferTemplate().slice();
  2372. }
  2373. }
  2374. }
  2375. writeBuffer(input, buffer, undefined, e);
  2376. }
  2377. }
  2378. },
  2379. mouseenterEvent: function (e) {
  2380. var input = this;
  2381. mouseEnter = true;
  2382. if (document.activeElement !== input && opts.showMaskOnHover) {
  2383. if (input.inputmask._valueGet() !== getBuffer().join("")) {
  2384. writeBuffer(input, getBuffer());
  2385. }
  2386. }
  2387. },
  2388. submitEvent: function (e) { //trigger change on submit if any
  2389. if (undoValue !== getBuffer().join("")) {
  2390. $el.trigger("change");
  2391. }
  2392. if (opts.clearMaskOnLostFocus && getLastValidPosition() === -1 && el.inputmask._valueGet && el.inputmask._valueGet() === getBufferTemplate().join("")) {
  2393. el.inputmask._valueSet(""); //clear masktemplete on submit and still has focus
  2394. }
  2395. if (opts.removeMaskOnSubmit) {
  2396. el.inputmask._valueSet(el.inputmask.unmaskedvalue(), true);
  2397. setTimeout(function () {
  2398. writeBuffer(el, getBuffer());
  2399. }, 0);
  2400. }
  2401. },
  2402. resetEvent: function (e) {
  2403. el.inputmask.refreshValue = true; //indicate a forced refresh when there is a call to the value before leaving the triggering event fn
  2404. setTimeout(function () {
  2405. $el.trigger("setvalue");
  2406. }, 0);
  2407. }
  2408. };
  2409. function initializeColorMask(input) {
  2410. function findCaretPos(clientx) {
  2411. //calculate text width
  2412. var e = document.createElement('span'), caretPos;
  2413. for (var style in computedStyle) { //clone styles
  2414. if (isNaN(style) && style.indexOf("font") !== -1) {
  2415. e.style[style] = computedStyle[style];
  2416. }
  2417. }
  2418. e.style.textTransform = computedStyle.textTransform;
  2419. e.style.letterSpacing = computedStyle.letterSpacing;
  2420. e.style.position = "absolute";
  2421. e.style.height = "auto";
  2422. e.style.width = "auto";
  2423. e.style.visibility = "hidden";
  2424. e.style.whiteSpace = "nowrap";
  2425. document.body.appendChild(e);
  2426. var inputText = input.inputmask._valueGet(), previousWidth = 0, itl;
  2427. for (caretPos = 0, itl = inputText.length; caretPos <= itl; caretPos++) {
  2428. e.innerHTML += inputText.charAt(caretPos) || "_";
  2429. if (e.offsetWidth >= clientx) {
  2430. var offset1 = (clientx - previousWidth);
  2431. var offset2 = e.offsetWidth - clientx;
  2432. e.innerHTML = inputText.charAt(caretPos);
  2433. offset1 -= (e.offsetWidth / 3);
  2434. caretPos = offset1 < offset2 ? caretPos - 1 : caretPos;
  2435. break;
  2436. }
  2437. previousWidth = e.offsetWidth;
  2438. }
  2439. document.body.removeChild(e);
  2440. return caretPos;
  2441. }
  2442. function position() {
  2443. colorMask.style.position = "absolute";
  2444. colorMask.style.top = offset.top + "px";
  2445. colorMask.style.left = offset.left + "px";
  2446. colorMask.style.width = parseInt(input.offsetWidth) - parseInt(computedStyle.paddingLeft) - parseInt(computedStyle.paddingRight) - parseInt(computedStyle.borderLeftWidth) - parseInt(computedStyle.borderRightWidth) + "px";
  2447. colorMask.style.height = parseInt(input.offsetHeight) - parseInt(computedStyle.paddingTop) - parseInt(computedStyle.paddingBottom) - parseInt(computedStyle.borderTopWidth) - parseInt(computedStyle.borderBottomWidth) + "px";
  2448. colorMask.style.lineHeight = colorMask.style.height;
  2449. colorMask.style.zIndex = isNaN(computedStyle.zIndex) ? -1 : computedStyle.zIndex - 1;
  2450. colorMask.style.webkitAppearance = "textfield";
  2451. colorMask.style.mozAppearance = "textfield";
  2452. colorMask.style.Appearance = "textfield";
  2453. }
  2454. var offset = $(input).position(),
  2455. computedStyle = (input.ownerDocument.defaultView || window).getComputedStyle(input, null),
  2456. parentNode = input.parentNode;
  2457. colorMask = document.createElement("div");
  2458. document.body.appendChild(colorMask); //insert at body to prevent css clash :last-child for example
  2459. for (var style in computedStyle) { //clone styles
  2460. if (isNaN(style) && style !== "cssText" && style.indexOf("webkit") == -1) {
  2461. colorMask.style[style] = computedStyle[style];
  2462. }
  2463. }
  2464. //restyle input
  2465. input.style.backgroundColor = "transparent";
  2466. input.style.color = "transparent";
  2467. input.style.webkitAppearance = "caret";
  2468. input.style.mozAppearance = "caret";
  2469. input.style.Appearance = "caret";
  2470. position();
  2471. //event passthrough
  2472. $(window).on("resize", function (e) {
  2473. offset = $(input).position();
  2474. computedStyle = (input.ownerDocument.defaultView || window).getComputedStyle(input, null);
  2475. position();
  2476. });
  2477. $(input).on("click", function (e) {
  2478. caret(input, findCaretPos(e.clientX));
  2479. return EventHandlers.clickEvent.call(this, [e]);
  2480. });
  2481. $(input).on("keydown", function (e) {
  2482. if (!e.shiftKey && opts.insertMode !== false) {
  2483. setTimeout(function () {
  2484. renderColorMask(input);
  2485. }, 0);
  2486. }
  2487. });
  2488. }
  2489. function renderColorMask(input, buffer, caretPos) {
  2490. function handleStatic() {
  2491. if (!isStatic && (test.fn === null || testPos.input === undefined)) {
  2492. isStatic = true;
  2493. maskTemplate += "<span class='im-static''>"
  2494. } else if (isStatic && (test.fn !== null && testPos.input !== undefined)) {
  2495. isStatic = false;
  2496. maskTemplate += "</span>"
  2497. }
  2498. }
  2499. if (colorMask !== undefined) {
  2500. buffer = buffer || getBuffer();
  2501. if (caretPos === undefined) {
  2502. caretPos = caret(input);
  2503. } else if (caretPos.begin === undefined) {
  2504. caretPos = {begin: caretPos, end: caretPos};
  2505. }
  2506. var maskTemplate = "", isStatic = false;
  2507. if (buffer != "") {
  2508. var ndxIntlzr, pos = 0,
  2509. test, testPos, lvp = getLastValidPosition();
  2510. do {
  2511. if (pos === caretPos.begin && document.activeElement === input) {
  2512. maskTemplate += "<span class='im-caret' style='border-right-width: 1px;border-right-style: solid;'></span>";
  2513. }
  2514. if (getMaskSet().validPositions[pos]) {
  2515. testPos = getMaskSet().validPositions[pos];
  2516. test = testPos.match;
  2517. ndxIntlzr = testPos.locator.slice();
  2518. handleStatic();
  2519. maskTemplate += testPos.input;
  2520. } else {
  2521. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  2522. test = testPos.match;
  2523. ndxIntlzr = testPos.locator.slice();
  2524. if (opts.jitMasking === false || pos < lvp || (typeof opts.jitMasking === "number" && isFinite(opts.jitMasking) && opts.jitMasking > pos)) {
  2525. handleStatic();
  2526. maskTemplate += getPlaceholder(pos, test);
  2527. }
  2528. }
  2529. pos++;
  2530. } while ((maxLength === undefined || pos < maxLength) && (test.fn !== null || test.def !== "") || lvp > pos);
  2531. }
  2532. colorMask.innerHTML = maskTemplate;
  2533. }
  2534. }
  2535. function mask(elem) {
  2536. function isElementTypeSupported(input, opts) {
  2537. function patchValueProperty(npt) {
  2538. var valueGet;
  2539. var valueSet;
  2540. function patchValhook(type) {
  2541. if ($.valHooks && ($.valHooks[type] === undefined || $.valHooks[type].inputmaskpatch !== true)) {
  2542. var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) {
  2543. return elem.value;
  2544. };
  2545. var valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
  2546. elem.value = value;
  2547. return elem;
  2548. };
  2549. $.valHooks[type] = {
  2550. get: function (elem) {
  2551. if (elem.inputmask) {
  2552. if (elem.inputmask.opts.autoUnmask) {
  2553. return elem.inputmask.unmaskedvalue();
  2554. } else {
  2555. var result = valhookGet(elem);
  2556. return getLastValidPosition(undefined, undefined, elem.inputmask.maskset.validPositions) !== -1 || opts.nullable !== true ? result : "";
  2557. }
  2558. } else return valhookGet(elem);
  2559. },
  2560. set: function (elem, value) {
  2561. var $elem = $(elem),
  2562. result;
  2563. result = valhookSet(elem, value);
  2564. if (elem.inputmask) {
  2565. $elem.trigger("setvalue");
  2566. }
  2567. return result;
  2568. },
  2569. inputmaskpatch: true
  2570. };
  2571. }
  2572. }
  2573. function getter() {
  2574. if (this.inputmask) {
  2575. return this.inputmask.opts.autoUnmask ?
  2576. this.inputmask.unmaskedvalue() :
  2577. (getLastValidPosition() !== -1 || opts.nullable !== true ?
  2578. (document.activeElement === this && opts.clearMaskOnLostFocus ?
  2579. (isRTL ? clearOptionalTail(getBuffer().slice()).reverse() : clearOptionalTail(getBuffer().slice())).join("") :
  2580. valueGet.call(this)) :
  2581. "");
  2582. } else return valueGet.call(this);
  2583. }
  2584. function setter(value) {
  2585. valueSet.call(this, value);
  2586. if (this.inputmask) {
  2587. $(this).trigger("setvalue");
  2588. }
  2589. }
  2590. function installNativeValueSetFallback(npt) {
  2591. EventRuler.on(npt, "mouseenter", function (event) {
  2592. var $input = $(this),
  2593. input = this,
  2594. value = input.inputmask._valueGet();
  2595. if (value !== getBuffer().join("") /*&& getLastValidPosition() > 0*/) {
  2596. $input.trigger("setvalue");
  2597. }
  2598. });
  2599. }
  2600. if (!npt.inputmask.__valueGet) {
  2601. if (opts.noValuePatching !== true) {
  2602. if (Object.getOwnPropertyDescriptor) {
  2603. if (typeof Object.getPrototypeOf !== "function") {
  2604. Object.getPrototypeOf = typeof "test".__proto__ === "object" ? function (object) {
  2605. return object.__proto__;
  2606. } : function (object) {
  2607. return object.constructor.prototype;
  2608. };
  2609. }
  2610. var valueProperty = Object.getPrototypeOf ? Object.getOwnPropertyDescriptor(Object.getPrototypeOf(npt), "value") : undefined;
  2611. if (valueProperty && valueProperty.get && valueProperty.set) {
  2612. valueGet = valueProperty.get;
  2613. valueSet = valueProperty.set;
  2614. Object.defineProperty(npt, "value", {
  2615. get: getter,
  2616. set: setter,
  2617. configurable: true
  2618. });
  2619. } else if (npt.tagName !== "INPUT") {
  2620. valueGet = function () {
  2621. return this.textContent;
  2622. };
  2623. valueSet = function (value) {
  2624. this.textContent = value;
  2625. };
  2626. Object.defineProperty(npt, "value", {
  2627. get: getter,
  2628. set: setter,
  2629. configurable: true
  2630. });
  2631. }
  2632. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  2633. valueGet = npt.__lookupGetter__("value");
  2634. valueSet = npt.__lookupSetter__("value");
  2635. npt.__defineGetter__("value", getter);
  2636. npt.__defineSetter__("value", setter);
  2637. }
  2638. npt.inputmask.__valueGet = valueGet; //store native property getter
  2639. npt.inputmask.__valueSet = valueSet; //store native property setter
  2640. }
  2641. npt.inputmask._valueGet = function (overruleRTL) {
  2642. return isRTL && overruleRTL !== true ? valueGet.call(this.el).split("").reverse().join("") : valueGet.call(this.el);
  2643. };
  2644. npt.inputmask._valueSet = function (value, overruleRTL) { //null check is needed for IE8 => otherwise converts to "null"
  2645. valueSet.call(this.el, (value === null || value === undefined) ? "" : ((overruleRTL !== true && isRTL) ? value.split("").reverse().join("") : value));
  2646. };
  2647. if (valueGet === undefined) { //jquery.val fallback
  2648. valueGet = function () {
  2649. return this.value;
  2650. };
  2651. valueSet = function (value) {
  2652. this.value = value;
  2653. };
  2654. patchValhook(npt.type);
  2655. installNativeValueSetFallback(npt);
  2656. }
  2657. }
  2658. }
  2659. var elementType = input.getAttribute("type");
  2660. var isSupported = (input.tagName === "INPUT" && $.inArray(elementType, opts.supportsInputType) !== -1) || input.isContentEditable || input.tagName === "TEXTAREA";
  2661. if (!isSupported) {
  2662. if (input.tagName === "INPUT") {
  2663. var el = document.createElement("input");
  2664. el.setAttribute("type", elementType);
  2665. isSupported = el.type === "text"; //apply mask only if the type is not natively supported
  2666. el = null;
  2667. } else isSupported = "partial";
  2668. }
  2669. if (isSupported !== false) {
  2670. patchValueProperty(input);
  2671. }
  2672. return isSupported;
  2673. }
  2674. //unbind all events - to make sure that no other mask will interfere when re-masking
  2675. EventRuler.off(elem);
  2676. var isSupported = isElementTypeSupported(elem, opts);
  2677. if (isSupported !== false) {
  2678. el = elem;
  2679. $el = $(el);
  2680. if (el.dir === "rtl" || opts.rightAlign) {
  2681. el.style.textAlign = "right";
  2682. }
  2683. if (el.dir === "rtl" || opts.numericInput) {
  2684. el.dir = "ltr";
  2685. el.removeAttribute("dir");
  2686. el.inputmask.isRTL = true;
  2687. isRTL = true;
  2688. }
  2689. if (opts.colorMask === true) {
  2690. initializeColorMask(el);
  2691. }
  2692. if (android) {
  2693. if (el.hasOwnProperty("inputmode")) {
  2694. el.inputmode = opts.inputmode;
  2695. el.setAttribute("inputmode", opts.inputmode);
  2696. }
  2697. if (opts.androidHack === "rtfm") {
  2698. if (opts.colorMask !== true) {
  2699. initializeColorMask(el);
  2700. }
  2701. el.type = "password";
  2702. }
  2703. }
  2704. if (isSupported === true) {
  2705. //bind events
  2706. EventRuler.on(el, "submit", EventHandlers.submitEvent);
  2707. EventRuler.on(el, "reset", EventHandlers.resetEvent);
  2708. EventRuler.on(el, "mouseenter", EventHandlers.mouseenterEvent);
  2709. EventRuler.on(el, "blur", EventHandlers.blurEvent);
  2710. EventRuler.on(el, "focus", EventHandlers.focusEvent);
  2711. EventRuler.on(el, "mouseleave", EventHandlers.mouseleaveEvent);
  2712. if (opts.colorMask !== true)
  2713. EventRuler.on(el, "click", EventHandlers.clickEvent);
  2714. EventRuler.on(el, "dblclick", EventHandlers.dblclickEvent);
  2715. EventRuler.on(el, "paste", EventHandlers.pasteEvent);
  2716. EventRuler.on(el, "dragdrop", EventHandlers.pasteEvent);
  2717. EventRuler.on(el, "drop", EventHandlers.pasteEvent);
  2718. EventRuler.on(el, "cut", EventHandlers.cutEvent);
  2719. EventRuler.on(el, "complete", opts.oncomplete);
  2720. EventRuler.on(el, "incomplete", opts.onincomplete);
  2721. EventRuler.on(el, "cleared", opts.oncleared);
  2722. if (!android || opts.inputEventOnly !== true) {
  2723. EventRuler.on(el, "keydown", EventHandlers.keydownEvent);
  2724. EventRuler.on(el, "keypress", EventHandlers.keypressEvent);
  2725. }
  2726. EventRuler.on(el, "compositionstart", $.noop);
  2727. EventRuler.on(el, "compositionupdate", $.noop);
  2728. EventRuler.on(el, "compositionend", $.noop);
  2729. EventRuler.on(el, "keyup", $.noop);
  2730. EventRuler.on(el, "input", EventHandlers.inputFallBackEvent);
  2731. EventRuler.on(el, "beforeinput", $.noop); //https://github.com/w3c/input-events - to implement
  2732. }
  2733. EventRuler.on(el, "setvalue", EventHandlers.setValueEvent);
  2734. //apply mask
  2735. getBufferTemplate(); //initialize the buffer and getmasklength
  2736. if (el.inputmask._valueGet() !== "" || opts.clearMaskOnLostFocus === false || document.activeElement === el) {
  2737. var initialValue = $.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(el.inputmask._valueGet(), opts) || el.inputmask._valueGet()) : el.inputmask._valueGet();
  2738. checkVal(el, true, false, initialValue.split(""));
  2739. var buffer = getBuffer().slice();
  2740. undoValue = buffer.join("");
  2741. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  2742. if (isComplete(buffer) === false) {
  2743. if (opts.clearIncomplete) {
  2744. resetMaskSet();
  2745. }
  2746. }
  2747. if (opts.clearMaskOnLostFocus && document.activeElement !== el) {
  2748. if (getLastValidPosition() === -1) {
  2749. buffer = [];
  2750. } else {
  2751. clearOptionalTail(buffer);
  2752. }
  2753. }
  2754. writeBuffer(el, buffer);
  2755. if (document.activeElement === el) { //position the caret when in focus
  2756. caret(el, seekNext(getLastValidPosition()));
  2757. }
  2758. }
  2759. }
  2760. }
  2761. //action object
  2762. var valueBuffer;
  2763. if (actionObj !== undefined) {
  2764. switch (actionObj.action) {
  2765. case "isComplete":
  2766. el = actionObj.el;
  2767. return isComplete(getBuffer());
  2768. case "unmaskedvalue":
  2769. if (el === undefined || actionObj.value !== undefined) {
  2770. valueBuffer = actionObj.value;
  2771. valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(valueBuffer, opts) || valueBuffer) : valueBuffer).split("");
  2772. checkVal(undefined, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  2773. if ($.isFunction(opts.onBeforeWrite)) opts.onBeforeWrite(undefined, getBuffer(), 0, opts);
  2774. }
  2775. return unmaskedvalue(el);
  2776. case "mask":
  2777. mask(el);
  2778. break;
  2779. case "format":
  2780. valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(actionObj.value, opts) || actionObj.value) : actionObj.value).split("");
  2781. checkVal(undefined, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  2782. if ($.isFunction(opts.onBeforeWrite)) opts.onBeforeWrite(undefined, getBuffer(), 0, opts);
  2783. if (actionObj.metadata) {
  2784. return {
  2785. value: isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join(""),
  2786. metadata: maskScope.call(this, {
  2787. "action": "getmetadata"
  2788. }, maskset, opts)
  2789. };
  2790. }
  2791. return isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join("");
  2792. case "isValid":
  2793. if (actionObj.value) {
  2794. valueBuffer = actionObj.value.split("");
  2795. checkVal(undefined, false, true, isRTL ? valueBuffer.reverse() : valueBuffer);
  2796. } else {
  2797. actionObj.value = getBuffer().join("");
  2798. }
  2799. var buffer = getBuffer();
  2800. var rl = determineLastRequiredPosition(),
  2801. lmib = buffer.length - 1;
  2802. for (; lmib > rl; lmib--) {
  2803. if (isMask(lmib)) break;
  2804. }
  2805. buffer.splice(rl, lmib + 1 - rl);
  2806. return isComplete(buffer) && actionObj.value === getBuffer().join("");
  2807. case "getemptymask":
  2808. return getBufferTemplate().join("");
  2809. case "remove":
  2810. if (el) {
  2811. $el = $(el);
  2812. //writeout the unmaskedvalue
  2813. el.inputmask._valueSet(unmaskedvalue(el));
  2814. //unbind all events
  2815. EventRuler.off(el);
  2816. //restore the value property
  2817. var valueProperty;
  2818. if (Object.getOwnPropertyDescriptor && Object.getPrototypeOf) {
  2819. valueProperty = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el), "value");
  2820. if (valueProperty) {
  2821. if (el.inputmask.__valueGet) {
  2822. Object.defineProperty(el, "value", {
  2823. get: el.inputmask.__valueGet,
  2824. set: el.inputmask.__valueSet,
  2825. configurable: true
  2826. });
  2827. }
  2828. }
  2829. } else if (document.__lookupGetter__ && el.__lookupGetter__("value")) {
  2830. if (el.inputmask.__valueGet) {
  2831. el.__defineGetter__("value", el.inputmask.__valueGet);
  2832. el.__defineSetter__("value", el.inputmask.__valueSet);
  2833. }
  2834. }
  2835. //clear data
  2836. el.inputmask = undefined;
  2837. }
  2838. return el;
  2839. break;
  2840. case "getmetadata":
  2841. if ($.isArray(maskset.metadata)) {
  2842. var maskTarget = getMaskTemplate(true, 0, false).join("");
  2843. $.each(maskset.metadata, function (ndx, mtdt) {
  2844. if (mtdt.mask === maskTarget) {
  2845. maskTarget = mtdt;
  2846. return false;
  2847. }
  2848. });
  2849. return maskTarget;
  2850. }
  2851. return maskset.metadata;
  2852. }
  2853. }
  2854. }
  2855. //make inputmask available
  2856. return Inputmask;
  2857. }));