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