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