inputmask.js 177 KB

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