inputmask.js 176 KB

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