inputmask.js 177 KB

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