inputmask.js 174 KB

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