inputmask.js 180 KB

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