inputmask.js 169 KB

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