inputmask.js 185 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319
  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. function defaultCase() {
  417. if (openenings.length > 0) {
  418. currentOpeningToken = openenings[openenings.length - 1];
  419. insertTestDefinition(currentOpeningToken, m);
  420. if (currentOpeningToken.isAlternator) { //handle alternator a | b case
  421. alternator = openenings.pop();
  422. for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
  423. alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group
  424. }
  425. if (openenings.length > 0) {
  426. currentOpeningToken = openenings[openenings.length - 1];
  427. currentOpeningToken.matches.push(alternator);
  428. } else {
  429. currentToken.matches.push(alternator);
  430. }
  431. }
  432. } else {
  433. insertTestDefinition(currentToken, m);
  434. }
  435. }
  436. function reverseTokens(maskToken) {
  437. function reverseStatic(st) {
  438. if (st === opts.optionalmarker.start) st = opts.optionalmarker.end;
  439. else if (st === opts.optionalmarker.end) st = opts.optionalmarker.start;
  440. else if (st === opts.groupmarker.start) st = opts.groupmarker.end;
  441. else if (st === opts.groupmarker.end) st = opts.groupmarker.start;
  442. return st;
  443. }
  444. maskToken.matches = maskToken.matches.reverse();
  445. for (var match in maskToken.matches) {
  446. if (maskToken.matches.hasOwnProperty(match)) {
  447. var intMatch = parseInt(match);
  448. if (maskToken.matches[match].isQuantifier && maskToken.matches[intMatch + 1] && maskToken.matches[intMatch + 1].isGroup) { //reposition quantifier
  449. var qt = maskToken.matches[match];
  450. maskToken.matches.splice(match, 1);
  451. maskToken.matches.splice(intMatch + 1, 0, qt);
  452. }
  453. if (maskToken.matches[match].matches !== undefined) {
  454. maskToken.matches[match] = reverseTokens(maskToken.matches[match]);
  455. } else {
  456. maskToken.matches[match] = reverseStatic(maskToken.matches[match]);
  457. }
  458. }
  459. }
  460. return maskToken;
  461. }
  462. if (regexMask) {
  463. opts.optionalmarker.start = undefined;
  464. opts.optionalmarker.end = undefined;
  465. }
  466. while (match = regexMask ? regexTokenizer.exec(mask) : tokenizer.exec(mask)) {
  467. m = match[0];
  468. if (regexMask) {
  469. switch (m.charAt(0)) {
  470. //Quantifier
  471. case "?":
  472. m = "{0,1}";
  473. break;
  474. case "+":
  475. case "*":
  476. m = "{" + m + "}";
  477. break;
  478. }
  479. }
  480. if (escaped) {
  481. defaultCase();
  482. continue;
  483. }
  484. switch (m.charAt(0)) {
  485. case opts.escapeChar:
  486. escaped = true;
  487. if (regexMask) {
  488. defaultCase();
  489. }
  490. break;
  491. case opts.optionalmarker.end:
  492. // optional closing
  493. case opts.groupmarker.end:
  494. // Group closing
  495. openingToken = openenings.pop();
  496. openingToken.openGroup = false; //mark group as complete
  497. if (openingToken !== undefined) {
  498. if (openenings.length > 0) {
  499. currentOpeningToken = openenings[openenings.length - 1];
  500. currentOpeningToken.matches.push(openingToken);
  501. if (currentOpeningToken.isAlternator) { //handle alternator (a) | (b) case
  502. alternator = openenings.pop();
  503. for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
  504. alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group
  505. alternator.matches[mndx].alternatorGroup = false;
  506. }
  507. if (openenings.length > 0) {
  508. currentOpeningToken = openenings[openenings.length - 1];
  509. currentOpeningToken.matches.push(alternator);
  510. } else {
  511. currentToken.matches.push(alternator);
  512. }
  513. }
  514. } else {
  515. currentToken.matches.push(openingToken);
  516. }
  517. } else defaultCase();
  518. break;
  519. case opts.optionalmarker.start:
  520. // optional opening
  521. openenings.push(new MaskToken(false, true));
  522. break;
  523. case opts.groupmarker.start:
  524. // Group opening
  525. openenings.push(new MaskToken(true));
  526. break;
  527. case opts.quantifiermarker.start:
  528. //Quantifier
  529. var quantifier = new MaskToken(false, false, true);
  530. m = m.replace(/[{}]/g, "");
  531. var mq = m.split(","),
  532. mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]),
  533. mq1 = mq.length === 1 ? mq0 : (isNaN(mq[1]) ? mq[1] : parseInt(mq[1]));
  534. if (mq1 === "*" || mq1 === "+") {
  535. mq0 = mq1 === "*" ? 0 : 1;
  536. }
  537. quantifier.quantifier = {
  538. min: mq0,
  539. max: mq1
  540. };
  541. if (openenings.length > 0) {
  542. var matches = openenings[openenings.length - 1].matches;
  543. match = matches.pop();
  544. if (!match.isGroup) {
  545. groupToken = new MaskToken(true);
  546. groupToken.matches.push(match);
  547. match = groupToken;
  548. }
  549. matches.push(match);
  550. matches.push(quantifier);
  551. } else {
  552. match = currentToken.matches.pop();
  553. if (!match.isGroup) {
  554. if (regexMask && match.fn === null) {
  555. if (match.def === ".") match.fn = new RegExp(match.def, opts.casing ? "i" : "");
  556. }
  557. groupToken = new MaskToken(true);
  558. groupToken.matches.push(match);
  559. match = groupToken;
  560. }
  561. currentToken.matches.push(match);
  562. currentToken.matches.push(quantifier);
  563. }
  564. break;
  565. case opts.alternatormarker:
  566. if (openenings.length > 0) {
  567. currentOpeningToken = openenings[openenings.length - 1];
  568. var subToken = currentOpeningToken.matches[currentOpeningToken.matches.length - 1];
  569. if (currentOpeningToken.openGroup && //regexp alt syntax
  570. (subToken.matches === undefined || (subToken.isGroup === false && subToken.isAlternator === false))) { //alternations within group
  571. lastMatch = openenings.pop();
  572. } else {
  573. lastMatch = currentOpeningToken.matches.pop();
  574. }
  575. } else {
  576. lastMatch = currentToken.matches.pop();
  577. }
  578. if (lastMatch.isAlternator) {
  579. openenings.push(lastMatch);
  580. } else {
  581. if (lastMatch.alternatorGroup) {
  582. alternator = openenings.pop();
  583. lastMatch.alternatorGroup = false;
  584. } else {
  585. alternator = new MaskToken(false, false, false, true);
  586. }
  587. alternator.matches.push(lastMatch);
  588. openenings.push(alternator);
  589. if (lastMatch.openGroup) { //regexp alt syntax
  590. lastMatch.openGroup = false;
  591. var alternatorGroup = new MaskToken(true);
  592. alternatorGroup.alternatorGroup = true;
  593. openenings.push(alternatorGroup);
  594. }
  595. }
  596. break;
  597. default:
  598. defaultCase();
  599. }
  600. }
  601. while (openenings.length > 0) {
  602. openingToken = openenings.pop();
  603. currentToken.matches.push(openingToken);
  604. }
  605. if (currentToken.matches.length > 0) {
  606. verifyGroupMarker(currentToken);
  607. maskTokens.push(currentToken);
  608. }
  609. if (opts.numericInput || opts.isRTL) {
  610. reverseTokens(maskTokens[0]);
  611. }
  612. // console.log(JSON.stringify(maskTokens));
  613. return maskTokens;
  614. }
  615. };
  616. //apply defaults, definitions, aliases
  617. Inputmask.extendDefaults = function (options) {
  618. $.extend(true, Inputmask.prototype.defaults, options);
  619. };
  620. Inputmask.extendDefinitions = function (definition) {
  621. $.extend(true, Inputmask.prototype.definitions, definition);
  622. };
  623. Inputmask.extendAliases = function (alias) {
  624. $.extend(true, Inputmask.prototype.aliases, alias);
  625. };
  626. //static fn on inputmask
  627. Inputmask.format = function (value, options, metadata) {
  628. return Inputmask(options).format(value, metadata);
  629. };
  630. Inputmask.unmask = function (value, options) {
  631. return Inputmask(options).unmaskedvalue(value);
  632. };
  633. Inputmask.isValid = function (value, options) {
  634. return Inputmask(options).isValid(value);
  635. };
  636. Inputmask.remove = function (elems) {
  637. $.each(elems, function (ndx, el) {
  638. if (el.inputmask) el.inputmask.remove();
  639. });
  640. };
  641. Inputmask.escapeRegex = function (str) {
  642. var specials = ["/", ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\", "$", "^"];
  643. return str.replace(new RegExp("(\\" + specials.join("|\\") + ")", "gim"), "\\$1");
  644. };
  645. Inputmask.keyCode = {
  646. ALT: 18,
  647. BACKSPACE: 8,
  648. BACKSPACE_SAFARI: 127,
  649. CAPS_LOCK: 20,
  650. COMMA: 188,
  651. COMMAND: 91,
  652. COMMAND_LEFT: 91,
  653. COMMAND_RIGHT: 93,
  654. CONTROL: 17,
  655. DELETE: 46,
  656. DOWN: 40,
  657. END: 35,
  658. ENTER: 13,
  659. ESCAPE: 27,
  660. HOME: 36,
  661. INSERT: 45,
  662. LEFT: 37,
  663. MENU: 93,
  664. NUMPAD_ADD: 107,
  665. NUMPAD_DECIMAL: 110,
  666. NUMPAD_DIVIDE: 111,
  667. NUMPAD_ENTER: 108,
  668. NUMPAD_MULTIPLY: 106,
  669. NUMPAD_SUBTRACT: 109,
  670. PAGE_DOWN: 34,
  671. PAGE_UP: 33,
  672. PERIOD: 190,
  673. RIGHT: 39,
  674. SHIFT: 16,
  675. SPACE: 32,
  676. TAB: 9,
  677. UP: 38,
  678. WINDOWS: 91,
  679. X: 88
  680. };
  681. function resolveAlias(aliasStr, options, opts) {
  682. var aliasDefinition = Inputmask.prototype.aliases[aliasStr];
  683. if (aliasDefinition) {
  684. if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias, undefined, opts); //alias is another alias
  685. $.extend(true, opts, aliasDefinition); //merge alias definition in the options
  686. $.extend(true, opts, options); //reapply extra given options
  687. return true;
  688. } else //alias not found - try as mask
  689. if (opts.mask === null) {
  690. opts.mask = aliasStr;
  691. }
  692. return false;
  693. }
  694. function generateMaskSet(opts, nocache) {
  695. function generateMask(mask, metadata, opts) {
  696. var regexMask = false;
  697. if (mask === null || mask === "") {
  698. regexMask = opts.regex !== null;
  699. if (regexMask) {
  700. mask = opts.regex;
  701. mask = mask.replace(/^(\^)(.*)(\$)$/, "$2");
  702. } else {
  703. regexMask = true;
  704. mask = ".*";
  705. }
  706. }
  707. if (mask.length === 1 && opts.greedy === false && opts.repeat !== 0) {
  708. opts.placeholder = "";
  709. } //hide placeholder with single non-greedy mask
  710. if (opts.repeat > 0 || opts.repeat === "*" || opts.repeat === "+") {
  711. var repeatStart = opts.repeat === "*" ? 0 : (opts.repeat === "+" ? 1 : opts.repeat);
  712. mask = opts.groupmarker.start + mask + opts.groupmarker.end + opts.quantifiermarker.start + repeatStart + "," + opts.repeat + opts.quantifiermarker.end;
  713. }
  714. // console.log(mask);
  715. var masksetDefinition,
  716. maskdefKey = regexMask ? "regex_" + opts.regex : (opts.numericInput ? mask.split("").reverse().join("") : mask);
  717. if (Inputmask.prototype.masksCache[maskdefKey] === undefined || nocache === true) {
  718. masksetDefinition = {
  719. "mask": mask,
  720. "maskToken": Inputmask.prototype.analyseMask(mask, regexMask, opts),
  721. "validPositions": {},
  722. "_buffer": undefined,
  723. "buffer": undefined,
  724. "tests": {},
  725. "metadata": metadata,
  726. maskLength: undefined
  727. };
  728. if (nocache !== true) {
  729. Inputmask.prototype.masksCache[maskdefKey] = masksetDefinition;
  730. masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[maskdefKey]);
  731. }
  732. } else masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[maskdefKey]);
  733. return masksetDefinition;
  734. }
  735. var ms;
  736. if ($.isFunction(opts.mask)) { //allow mask to be a preprocessing fn - should return a valid mask
  737. opts.mask = opts.mask(opts);
  738. }
  739. if ($.isArray(opts.mask)) {
  740. if (opts.mask.length > 1) {
  741. opts.keepStatic = opts.keepStatic === null ? true : opts.keepStatic; //enable by default when passing multiple masks when the option is not explicitly specified
  742. var altMask = opts.groupmarker.start;
  743. $.each(opts.numericInput ? opts.mask.reverse() : opts.mask, function (ndx, msk) {
  744. if (altMask.length > 1) {
  745. altMask += opts.groupmarker.end + opts.alternatormarker + opts.groupmarker.start;
  746. }
  747. if (msk.mask !== undefined && !$.isFunction(msk.mask)) {
  748. altMask += msk.mask;
  749. } else {
  750. altMask += msk;
  751. }
  752. });
  753. altMask += opts.groupmarker.end;
  754. // console.log(altMask);
  755. return generateMask(altMask, opts.mask, opts);
  756. } else opts.mask = opts.mask.pop();
  757. }
  758. if (opts.mask && opts.mask.mask !== undefined && !$.isFunction(opts.mask.mask)) {
  759. ms = generateMask(opts.mask.mask, opts.mask, opts);
  760. } else {
  761. ms = generateMask(opts.mask, opts.mask, opts);
  762. }
  763. return ms;
  764. };
  765. //masking scope
  766. //actionObj definition see below
  767. function maskScope(actionObj, maskset, opts) {
  768. maskset = maskset || this.maskset;
  769. opts = opts || this.opts;
  770. var inputmask = this,
  771. el = this.el,
  772. isRTL = this.isRTL,
  773. undoValue,
  774. $el,
  775. skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
  776. skipInputEvent = false, //skip when triggered from within inputmask
  777. ignorable = false,
  778. maxLength,
  779. mouseEnter = false,
  780. colorMask;
  781. //maskset helperfunctions
  782. function getMaskTemplate(baseOnInput, minimalPos, includeMode) {
  783. //includeMode true => input, undefined => placeholder, false => mask
  784. minimalPos = minimalPos || 0;
  785. var maskTemplate = [],
  786. ndxIntlzr, pos = 0,
  787. test, testPos, lvp = getLastValidPosition();
  788. do {
  789. if (baseOnInput === true && getMaskSet().validPositions[pos]) {
  790. testPos = getMaskSet().validPositions[pos];
  791. test = testPos.match;
  792. ndxIntlzr = testPos.locator.slice();
  793. maskTemplate.push(includeMode === true ? testPos.input : includeMode === false ? test.nativeDef : getPlaceholder(pos, test));
  794. } else {
  795. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  796. test = testPos.match;
  797. ndxIntlzr = testPos.locator.slice();
  798. if (opts.jitMasking === false || pos < lvp || (typeof opts.jitMasking === "number" && isFinite(opts.jitMasking) && opts.jitMasking > pos)) {
  799. maskTemplate.push(includeMode === false ? test.nativeDef : getPlaceholder(pos, test));
  800. }
  801. }
  802. pos++;
  803. } while ((maxLength === undefined || pos < maxLength) && (test.fn !== null || test.def !== "") || minimalPos > pos);
  804. if (maskTemplate[maskTemplate.length - 1] === "") {
  805. maskTemplate.pop(); //drop the last one which is empty
  806. }
  807. getMaskSet().maskLength = pos + 1;
  808. return maskTemplate;
  809. }
  810. function getMaskSet() {
  811. return maskset;
  812. }
  813. function resetMaskSet(soft) {
  814. var maskset = getMaskSet();
  815. maskset.buffer = undefined;
  816. if (soft !== true) {
  817. // maskset._buffer = undefined;
  818. maskset.validPositions = {};
  819. maskset.p = 0;
  820. }
  821. }
  822. function getLastValidPosition(closestTo, strict, validPositions) {
  823. var before = -1,
  824. after = -1,
  825. valids = validPositions || getMaskSet().validPositions; //for use in valhook ~ context switch
  826. if (closestTo === undefined) closestTo = -1;
  827. for (var posNdx in valids) {
  828. var psNdx = parseInt(posNdx);
  829. if (valids[psNdx] && (strict || valids[psNdx].generatedInput !== true)) {
  830. if (psNdx <= closestTo) before = psNdx;
  831. if (psNdx >= closestTo) after = psNdx;
  832. }
  833. }
  834. return (before !== -1 && (closestTo - before) > 1) || after < closestTo ? before : after;
  835. }
  836. function stripValidPositions(start, end, nocheck, strict) {
  837. function IsEnclosedStatic(pos) {
  838. var posMatch = getMaskSet().validPositions[pos];
  839. if (posMatch !== undefined && posMatch.match.fn === null) {
  840. var prevMatch = getMaskSet().validPositions[pos - 1],
  841. nextMatch = getMaskSet().validPositions[pos + 1];
  842. return prevMatch !== undefined && nextMatch !== undefined;
  843. }
  844. return false;
  845. }
  846. var i, startPos = start,
  847. positionsClone = $.extend(true, {}, getMaskSet().validPositions),
  848. 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(undefined, true), 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],
  1052. dropMatch = false;
  1053. altMatch.alternation = altMatch.alternation || loopNdxCnt;
  1054. for (var ndx2 = 0; ndx2 < malternateMatches.length; ndx2++) {
  1055. var altMatch2 = malternateMatches[ndx2];
  1056. //verify equality
  1057. if (typeof altIndex !== "string" || $.inArray(altMatch.locator[altMatch.alternation].toString(), altIndexArr) !== -1) {
  1058. if (definitionCanMatchDefinition(altMatch, altMatch2)) {
  1059. dropMatch = true;
  1060. if (altMatch.alternation === altMatch2.alternation &&
  1061. altMatch2.locator[altMatch2.alternation].toString().indexOf(altMatch.locator[altMatch.alternation]) === -1) {
  1062. altMatch2.locator[altMatch2.alternation] = altMatch2.locator[altMatch2.alternation] + "," + altMatch.locator[altMatch.alternation];
  1063. altMatch2.alternation = altMatch.alternation; //we pass the alternation index => used in determineLastRequiredPosition
  1064. }
  1065. if (altMatch.match.nativeDef === altMatch2.match.def) {
  1066. altMatch.locator[altMatch.alternation] = altMatch2.locator[altMatch2.alternation];
  1067. malternateMatches.splice(malternateMatches.indexOf(altMatch2), 1, altMatch);
  1068. }
  1069. break;
  1070. } else if (altMatch.match.def === altMatch2.match.def) {
  1071. dropMatch = false;
  1072. break;
  1073. } else if (staticCanMatchDefinition(altMatch, altMatch2) || isSubsetOf(altMatch, altMatch2)) {
  1074. // console.log("case 5");
  1075. if (altMatch.alternation === altMatch2.alternation &&
  1076. altMatch.locator[altMatch.alternation].toString().indexOf(altMatch2.locator[altMatch2.alternation].toString().split("")[0]) === -1) {
  1077. //no alternation marker
  1078. altMatch.na = altMatch.na || altMatch.locator[altMatch.alternation].toString();
  1079. if (altMatch.na.indexOf(altMatch.locator[altMatch.alternation].toString().split("")[0]) === -1) {
  1080. altMatch.na = altMatch.na + "," + altMatch.locator[altMatch2.alternation].toString().split("")[0];
  1081. }
  1082. //insert match above general match
  1083. dropMatch = true;
  1084. altMatch.locator[altMatch.alternation] = altMatch2.locator[altMatch2.alternation].toString().split("")[0] + "," + altMatch.locator[altMatch.alternation];
  1085. malternateMatches.splice(malternateMatches.indexOf(altMatch2), 0, altMatch);
  1086. }
  1087. break;
  1088. }
  1089. }
  1090. }
  1091. if (!dropMatch) {
  1092. malternateMatches.push(altMatch);
  1093. }
  1094. }
  1095. }
  1096. if (typeof altIndex == "string") { //filter matches
  1097. malternateMatches = $.map(malternateMatches, function (lmnt, ndx) {
  1098. if (isFinite(ndx)) {
  1099. var mamatch,
  1100. alternation = lmnt.alternation,
  1101. altLocArr = lmnt.locator[alternation].toString().split(",");
  1102. lmnt.locator[alternation] = undefined;
  1103. lmnt.alternation = undefined;
  1104. for (var alndx = 0; alndx < altLocArr.length; alndx++) {
  1105. mamatch = $.inArray(altLocArr[alndx], altIndexArr) !== -1;
  1106. if (mamatch) { //rebuild the locator with valid entries
  1107. if (lmnt.locator[alternation] !== undefined) {
  1108. lmnt.locator[alternation] += ",";
  1109. lmnt.locator[alternation] += altLocArr[alndx];
  1110. } else lmnt.locator[alternation] = parseInt(altLocArr[alndx]);
  1111. lmnt.alternation = alternation;
  1112. }
  1113. }
  1114. if (lmnt.locator[alternation] !== undefined) return lmnt;
  1115. }
  1116. });
  1117. }
  1118. matches = currentMatches.concat(malternateMatches);
  1119. testPos = pos;
  1120. insertStop = matches.length > 0; //insert a stopelemnt when there is an alternate - needed for non-greedy option
  1121. match = malternateMatches.length > 0; //set correct match state
  1122. //cloneback
  1123. ndxInitializer = ndxInitializerClone.slice();
  1124. } else {
  1125. // if (alternateToken.matches[altIndex]) { //if not in the initial alternation => look further
  1126. match = handleMatch(alternateToken.matches[altIndex] || maskToken.matches[altIndex], [altIndex].concat(loopNdx), quantifierRecurse);
  1127. // } else match = false;
  1128. }
  1129. if (match) return true;
  1130. } else if (match.isQuantifier && quantifierRecurse !== maskToken.matches[$.inArray(match, maskToken.matches) - 1]) {
  1131. var qt = match;
  1132. for (var qndx = (ndxInitializer.length > 0) ? ndxInitializer.shift() : 0;
  1133. (qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max)) && testPos <= pos; qndx++) {
  1134. var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1];
  1135. match = handleMatch(tokenGroup, [qndx].concat(loopNdx), tokenGroup); //set the tokenGroup as quantifierRecurse marker
  1136. if (match) {
  1137. //get latest match
  1138. latestMatch = matches[matches.length - 1].match;
  1139. latestMatch.optionalQuantifier = qndx > (qt.quantifier.min - 1);
  1140. if (isFirstMatch(latestMatch, tokenGroup)) { //search for next possible match
  1141. if (qndx > (qt.quantifier.min - 1)) {
  1142. insertStop = true;
  1143. testPos = pos; //match the position after the group
  1144. break; //stop quantifierloop
  1145. } else return true;
  1146. } else {
  1147. return true;
  1148. }
  1149. }
  1150. }
  1151. } else {
  1152. match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  1153. if (match) return true;
  1154. }
  1155. } else {
  1156. testPos++;
  1157. }
  1158. }
  1159. for (var tndx = (ndxInitializer.length > 0 ? ndxInitializer.shift() : 0); tndx < maskToken.matches.length; tndx++) {
  1160. if (maskToken.matches[tndx].isQuantifier !== true) {
  1161. var match = handleMatch(maskToken.matches[tndx], [tndx].concat(loopNdx), quantifierRecurse);
  1162. if (match && testPos === pos) {
  1163. return match;
  1164. } else if (testPos > pos) {
  1165. break;
  1166. }
  1167. }
  1168. }
  1169. }
  1170. function mergeLocators(tests) {
  1171. var locator = [];
  1172. if (!$.isArray(tests)) tests = [tests];
  1173. if (tests.length > 0) {
  1174. if (tests[0].alternation === undefined) {
  1175. locator = determineTestTemplate(tests.slice()).locator.slice();
  1176. if (locator.length === 0) locator = tests[0].locator.slice();
  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. } else if (getMaskSet().validPositions[pos - 1].alternation === tests[0].alternation) {
  1203. return [determineTestTemplate(tests)];
  1204. } else if (getMaskSet().validPositions[pos - 1]) {
  1205. return [determineTestTemplate(tests)];
  1206. }
  1207. }
  1208. }
  1209. }
  1210. return tests;
  1211. }
  1212. if (pos > -1) {
  1213. if (ndxIntlzr === undefined) { //determine index initializer
  1214. var previousPos = pos - 1,
  1215. test;
  1216. while ((test = getMaskSet().validPositions[previousPos] || getMaskSet().tests[previousPos]) === undefined && previousPos > -1) {
  1217. previousPos--;
  1218. }
  1219. if (test !== undefined && previousPos > -1) {
  1220. ndxInitializer = mergeLocators(test);
  1221. cacheDependency = ndxInitializer.join("");
  1222. testPos = previousPos;
  1223. }
  1224. }
  1225. if (getMaskSet().tests[pos] && getMaskSet().tests[pos][0].cd === cacheDependency) { //cacheDependency is set on all tests, just check on the first
  1226. //console.log("cache hit " + pos + " - " + ndxIntlzr);
  1227. return filterTests(getMaskSet().tests[pos]);
  1228. }
  1229. for (var mtndx = ndxInitializer.shift(); mtndx < maskTokens.length; mtndx++) {
  1230. var match = resolveTestFromToken(maskTokens[mtndx], ndxInitializer, [mtndx]);
  1231. if ((match && testPos === pos) || testPos > pos) {
  1232. break;
  1233. }
  1234. }
  1235. }
  1236. if (matches.length === 0 || insertStop) {
  1237. matches.push({
  1238. match: {
  1239. fn: null,
  1240. cardinality: 0,
  1241. optionality: true,
  1242. casing: null,
  1243. def: "",
  1244. placeholder: ""
  1245. },
  1246. locator: [],
  1247. cd: cacheDependency
  1248. });
  1249. }
  1250. if (ndxIntlzr !== undefined && getMaskSet().tests[pos]) { //prioritize full tests for caching
  1251. return filterTests($.extend(true, [], matches));
  1252. }
  1253. getMaskSet().tests[pos] = $.extend(true, [], matches); //set a clone to prevent overwriting some props
  1254. // console.log(pos + " - " + JSON.stringify(matches));
  1255. return filterTests(getMaskSet().tests[pos]);
  1256. }
  1257. function getBufferTemplate() {
  1258. if (getMaskSet()._buffer === undefined) {
  1259. //generate template
  1260. getMaskSet()._buffer = getMaskTemplate(false, 1);
  1261. if (getMaskSet().buffer === undefined) {
  1262. getMaskSet().buffer = getMaskSet()._buffer.slice();
  1263. }
  1264. }
  1265. return getMaskSet()._buffer;
  1266. }
  1267. function getBuffer(noCache) {
  1268. if (getMaskSet().buffer === undefined || noCache === true) {
  1269. getMaskSet().buffer = getMaskTemplate(true, getLastValidPosition(), true);
  1270. }
  1271. return getMaskSet().buffer;
  1272. }
  1273. function refreshFromBuffer(start, end, buffer) {
  1274. var i, p;
  1275. if (start === true) {
  1276. resetMaskSet();
  1277. start = 0;
  1278. end = buffer.length;
  1279. } else {
  1280. for (i = start; i < end; i++) {
  1281. delete getMaskSet().validPositions[i];
  1282. }
  1283. }
  1284. p = start;
  1285. for (i = start; i < end; i++) {
  1286. resetMaskSet(true); //prevents clobber from the buffer
  1287. if (buffer[i] !== opts.skipOptionalPartCharacter) {
  1288. var valResult = isValid(p, buffer[i], true, true);
  1289. if (valResult !== false) {
  1290. resetMaskSet(true);
  1291. p = valResult.caret !== undefined ? valResult.caret : valResult.pos + 1;
  1292. }
  1293. }
  1294. }
  1295. }
  1296. function casing(elem, test, pos) {
  1297. switch (opts.casing || test.casing) {
  1298. case "upper":
  1299. elem = elem.toUpperCase();
  1300. break;
  1301. case "lower":
  1302. elem = elem.toLowerCase();
  1303. break;
  1304. case "title":
  1305. var posBefore = getMaskSet().validPositions[pos - 1];
  1306. if (pos === 0 || posBefore && posBefore.input === String.fromCharCode(Inputmask.keyCode.SPACE)) {
  1307. elem = elem.toUpperCase();
  1308. } else {
  1309. elem = elem.toLowerCase();
  1310. }
  1311. break;
  1312. default:
  1313. if ($.isFunction(opts.casing)) {
  1314. var args = Array.prototype.slice.call(arguments);
  1315. args.push(getMaskSet().validPositions);
  1316. elem = opts.casing.apply(this, args);
  1317. }
  1318. }
  1319. return elem;
  1320. }
  1321. function checkAlternationMatch(altArr1, altArr2, na) {
  1322. var altArrC = opts.greedy ? altArr2 : altArr2.slice(0, 1),
  1323. isMatch = false,
  1324. 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. return rslt;
  1430. }
  1431. function alternate(pos, c, strict) {
  1432. var validPsClone = $.extend(true, {}, getMaskSet().validPositions),
  1433. lastAlt,
  1434. alternation,
  1435. isValidRslt = false,
  1436. altPos, prevAltPos, i, validPos, lAltPos = getLastValidPosition(),
  1437. 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,
  1580. needsValidation = false,
  1581. initialLength = getMaskSet().maskLength;
  1582. for (i = (j = pos); i <= lvp; i++) {
  1583. var t = positionsClone[i];
  1584. if (t !== undefined /*&& (t.generatedInput !== true || t.match.fn === null)*/ ) {
  1585. var posMatch = j;
  1586. while (posMatch < getMaskSet().maskLength && ((t.match.fn === null && vps[i] && (vps[i].match.optionalQuantifier === true || vps[i].match.optionality === true)) || t.match.fn != null)) {
  1587. posMatch++;
  1588. if (needsValidation === false && positionsClone[posMatch] && positionsClone[posMatch].match.def === t.match.def) { //obvious match
  1589. getMaskSet().validPositions[posMatch] = $.extend(true, {}, positionsClone[posMatch]);
  1590. getMaskSet().validPositions[posMatch].input = t.input;
  1591. fillMissingNonMask(posMatch);
  1592. j = posMatch;
  1593. valid = true;
  1594. } else if (positionCanMatchDefinition(posMatch, t.match.def)) { //validated match
  1595. var result = isValid(posMatch, t.input, true, true);
  1596. valid = result !== false;
  1597. j = (result.caret || result.insert) ? getLastValidPosition() : posMatch;
  1598. needsValidation = true;
  1599. } else {
  1600. valid = t.generatedInput === true;
  1601. if (!valid && posMatch >= getMaskSet().maskLength - 1) break;
  1602. }
  1603. if (getMaskSet().maskLength < initialLength) getMaskSet().maskLength = initialLength; //a bit hacky but the masklength is corrected later on
  1604. if (valid) break;
  1605. }
  1606. }
  1607. if (!valid) break;
  1608. }
  1609. if (!valid) {
  1610. getMaskSet().validPositions = $.extend(true, {}, positionsClone);
  1611. resetMaskSet(true);
  1612. return false;
  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. return position;
  1727. }
  1728. function seekPrevious(pos, newBlock) {
  1729. var position = pos,
  1730. 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. return position;
  1737. }
  1738. function getBufferElement(position) {
  1739. return getMaskSet().validPositions[position] === undefined ? getPlaceholder(position) : getMaskSet().validPositions[position].input;
  1740. }
  1741. function writeBuffer(input, buffer, caretPos, event, triggerInputEvent) {
  1742. if (event && $.isFunction(opts.onBeforeWrite)) {
  1743. // buffer = buffer.slice(); //prevent uncontrolled manipulation of the internal buffer
  1744. var result = opts.onBeforeWrite.call(inputmask, event, buffer, caretPos, opts);
  1745. if (result) {
  1746. if (result.refreshFromBuffer) {
  1747. var refresh = result.refreshFromBuffer;
  1748. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer || buffer);
  1749. buffer = getBuffer(true);
  1750. }
  1751. //only alter when intented !== undefined
  1752. if (caretPos !== undefined) caretPos = result.caret !== undefined ? result.caret : caretPos;
  1753. }
  1754. }
  1755. if (input !== undefined) {
  1756. input.inputmask._valueSet(buffer.join(""));
  1757. if (caretPos !== undefined && (event === undefined || event.type !== "blur")) {
  1758. if (android && event && event.type === "input") {
  1759. setTimeout(function () {
  1760. caret(input, caretPos);
  1761. }, 0);
  1762. } else caret(input, caretPos);
  1763. } else renderColorMask(input, caretPos, buffer.length === 0);
  1764. if (triggerInputEvent === true) {
  1765. skipInputEvent = true;
  1766. $(input).trigger("input");
  1767. }
  1768. }
  1769. }
  1770. function getPlaceholder(pos, test, returnPL) {
  1771. test = test || getTest(pos).match;
  1772. if (test.placeholder !== undefined || returnPL === true) {
  1773. return $.isFunction(test.placeholder) ? test.placeholder(opts) : test.placeholder;
  1774. } else if (test.fn === null) {
  1775. if (pos > -1 && getMaskSet().validPositions[pos] === undefined) {
  1776. var tests = getTests(pos),
  1777. staticAlternations = [],
  1778. prevTest;
  1779. if (tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0)) {
  1780. for (var i = 0; i < tests.length; i++) {
  1781. if (tests[i].match.optionality !== true && tests[i].match.optionalQuantifier !== true &&
  1782. (tests[i].match.fn === null || (prevTest === undefined || tests[i].match.fn.test(prevTest.match.def, getMaskSet(), pos, true, opts) !== false))) {
  1783. staticAlternations.push(tests[i]);
  1784. if (tests[i].match.fn === null) prevTest = tests[i];
  1785. if (staticAlternations.length > 1) {
  1786. if (/[0-9a-bA-Z]/.test(staticAlternations[0].match.def)) {
  1787. return opts.placeholder.charAt(pos % opts.placeholder.length);
  1788. }
  1789. }
  1790. }
  1791. }
  1792. }
  1793. }
  1794. return test.def;
  1795. }
  1796. return opts.placeholder.charAt(pos % opts.placeholder.length);
  1797. }
  1798. var EventRuler = {
  1799. on: function (input, eventName, eventHandler) {
  1800. var ev = function (e) {
  1801. // console.log("triggered " + e.type);
  1802. if (this.inputmask === undefined && this.nodeName !== "FORM") { //happens when cloning an object with jquery.clone
  1803. var imOpts = $.data(this, "_inputmask_opts");
  1804. if (imOpts)(new Inputmask(imOpts)).mask(this);
  1805. else EventRuler.off(this);
  1806. } 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))))) {
  1807. e.preventDefault();
  1808. } else {
  1809. switch (e.type) {
  1810. case "input":
  1811. if (skipInputEvent === true) {
  1812. skipInputEvent = false;
  1813. return e.preventDefault();
  1814. }
  1815. break;
  1816. case "keydown":
  1817. //Safari 5.1.x - modal dialog fires keypress twice workaround
  1818. skipKeyPressEvent = false;
  1819. skipInputEvent = false;
  1820. break;
  1821. case "keypress":
  1822. if (skipKeyPressEvent === true) {
  1823. return e.preventDefault();
  1824. }
  1825. skipKeyPressEvent = true;
  1826. break;
  1827. case "click":
  1828. if (iemobile || iphone) {
  1829. var that = this,
  1830. 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 radixPointHandler(input, inputValue, caretPos) {
  2052. //radixpoint tweak
  2053. if (inputValue.charAt(caretPos.begin - 1) === "." && opts.radixPoint !== "") {
  2054. inputValue = inputValue.split("");
  2055. inputValue[caretPos.begin - 1] = opts.radixPoint.charAt(0);
  2056. inputValue = inputValue.join("");
  2057. }
  2058. return inputValue;
  2059. }
  2060. function ieMobileHandler(input, inputValue, caretPos) {
  2061. if (iemobile) { //iemobile just sets the character at the end althought the caret position is correctly set
  2062. var inputChar = inputValue.replace(getBuffer().join(""), "");
  2063. if (inputChar.length === 1) {
  2064. var iv = inputValue.split("");
  2065. iv.splice(caretPos.begin, 0, inputChar);
  2066. inputValue = iv.join("");
  2067. }
  2068. }
  2069. return inputValue;
  2070. }
  2071. var input = this,
  2072. inputValue = input.inputmask._valueGet();
  2073. if (getBuffer().join("") !== inputValue) {
  2074. var caretPos = caret(input);
  2075. inputValue = radixPointHandler(input, inputValue, caretPos);
  2076. inputValue = ieMobileHandler(input, inputValue, caretPos);
  2077. if (caretPos.begin > inputValue.length) {
  2078. caret(input, inputValue.length);
  2079. caretPos = caret(input);
  2080. }
  2081. if (getBuffer().join("") !== inputValue) {
  2082. var buffer = getBuffer().join(""),
  2083. offset = inputValue.length > buffer.length ? -1 : 0,
  2084. frontPart = inputValue.substr(0, caretPos.begin),
  2085. backPart = inputValue.substr(caretPos.begin),
  2086. frontBufferPart = buffer.substr(0, caretPos.begin + offset),
  2087. backBufferPart = buffer.substr(caretPos.begin + offset);
  2088. //check if thare was a selection
  2089. var selection = caretPos,
  2090. entries = "",
  2091. isEntry = false;
  2092. if (frontPart !== frontBufferPart) {
  2093. var fpl = (isEntry = frontPart.length >= frontBufferPart.length) ? frontPart.length : frontBufferPart.length
  2094. for (var i = 0; frontPart.charAt(i) === frontBufferPart.charAt(i) && i < fpl; i++) {}
  2095. if (isEntry) {
  2096. if (offset === 0) selection.begin = i;
  2097. entries += frontPart.slice(i, selection.end);
  2098. }
  2099. }
  2100. if (backPart !== backBufferPart) {
  2101. if (backPart.length > backBufferPart.length) {
  2102. entries += backPart.slice(0, 1);
  2103. } else {
  2104. if (backPart.length < backBufferPart.length) {
  2105. selection.end += backBufferPart.length - backPart.length;
  2106. //hack around numeric alias & radixpoint
  2107. if (!isEntry && opts.radixPoint !== "" && backPart === "" && frontPart.charAt(selection.begin + offset - 1) === opts.radixPoint) {
  2108. selection.begin--;
  2109. entries = opts.radixPoint;
  2110. }
  2111. }
  2112. }
  2113. }
  2114. writeBuffer(input, getBuffer(), {
  2115. "begin": selection.begin + offset,
  2116. "end": selection.end + offset
  2117. });
  2118. if (entries.length > 0) {
  2119. $.each(entries.split(""), function (ndx, entry) {
  2120. var keypress = new $.Event("keypress");
  2121. keypress.which = entry.charCodeAt(0);
  2122. ignorable = false; //make sure ignorable is ignored ;-)
  2123. EventHandlers.keypressEvent.call(input, keypress);
  2124. });
  2125. } else {
  2126. if (selection.begin === selection.end - 1) {
  2127. selection.begin = seekPrevious(selection.begin + 1);
  2128. if (selection.begin === selection.end - 1) {
  2129. caret(input, selection.begin);
  2130. } else {
  2131. caret(input, selection.begin, selection.end);
  2132. }
  2133. }
  2134. var keydown = new $.Event("keydown");
  2135. keydown.keyCode = Inputmask.keyCode.DELETE;
  2136. EventHandlers.keydownEvent.call(input, keydown);
  2137. }
  2138. e.preventDefault();
  2139. }
  2140. }
  2141. },
  2142. setValueEvent: function (e) {
  2143. this.inputmask.refreshValue = false;
  2144. var input = this,
  2145. value = input.inputmask._valueGet(true);
  2146. if ($.isFunction(opts.onBeforeMask)) value = opts.onBeforeMask.call(inputmask, value, opts) || value;
  2147. value = value.split("");
  2148. checkVal(input, true, false, isRTL ? value.reverse() : value);
  2149. undoValue = getBuffer().join("");
  2150. if ((opts.clearMaskOnLostFocus || opts.clearIncomplete) && input.inputmask._valueGet() === getBufferTemplate().join("")) {
  2151. input.inputmask._valueSet("");
  2152. }
  2153. }
  2154. ,
  2155. focusEvent: function (e) {
  2156. var input = this,
  2157. nptValue = input.inputmask._valueGet();
  2158. if (opts.showMaskOnFocus && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue === ""))) {
  2159. if (input.inputmask._valueGet() !== getBuffer().join("")) {
  2160. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
  2161. } else if (mouseEnter === false) { //only executed on focus without mouseenter
  2162. caret(input, seekNext(getLastValidPosition()));
  2163. }
  2164. }
  2165. if (opts.positionCaretOnTab === true && mouseEnter === false && nptValue !== "") {
  2166. writeBuffer(input, getBuffer(), caret(input));
  2167. EventHandlers.clickEvent.apply(input, [e, true]);
  2168. }
  2169. undoValue = getBuffer().join("");
  2170. },
  2171. mouseleaveEvent: function (e) {
  2172. var input = this;
  2173. mouseEnter = false;
  2174. if (opts.clearMaskOnLostFocus && document.activeElement !== input) {
  2175. var buffer = getBuffer().slice(),
  2176. nptValue = input.inputmask._valueGet();
  2177. if (nptValue !== input.getAttribute("placeholder") && nptValue !== "") {
  2178. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  2179. buffer = [];
  2180. } else { //clearout optional tail of the mask
  2181. clearOptionalTail(buffer);
  2182. }
  2183. writeBuffer(input, buffer);
  2184. }
  2185. }
  2186. },
  2187. clickEvent: function (e, tabbed) {
  2188. function doRadixFocus(clickPos) {
  2189. if (opts.radixPoint !== "") {
  2190. var vps = getMaskSet().validPositions;
  2191. if (vps[clickPos] === undefined || (vps[clickPos].input === getPlaceholder(clickPos))) {
  2192. if (clickPos < seekNext(-1)) return true;
  2193. var radixPos = $.inArray(opts.radixPoint, getBuffer());
  2194. if (radixPos !== -1) {
  2195. for (var vp in vps) {
  2196. if (radixPos < vp && vps[vp].input !== getPlaceholder(vp)) {
  2197. return false;
  2198. }
  2199. }
  2200. return true;
  2201. }
  2202. }
  2203. }
  2204. return false;
  2205. }
  2206. var input = this;
  2207. setTimeout(function () { //needed for Chrome ~ initial selection clears after the clickevent
  2208. if (document.activeElement === input) {
  2209. var selectedCaret = caret(input);
  2210. if (tabbed) {
  2211. if (isRTL) {
  2212. selectedCaret.end = selectedCaret.begin;
  2213. } else {
  2214. selectedCaret.begin = selectedCaret.end;
  2215. }
  2216. }
  2217. if (selectedCaret.begin === selectedCaret.end) {
  2218. switch (opts.positionCaretOnClick) {
  2219. case "none":
  2220. break;
  2221. case "radixFocus":
  2222. if (doRadixFocus(selectedCaret.begin)) {
  2223. var radixPos = getBuffer().join("").indexOf(opts.radixPoint);
  2224. caret(input, opts.numericInput ? seekNext(radixPos) : radixPos);
  2225. break;
  2226. }
  2227. default: //lvp:
  2228. var clickPosition = selectedCaret.begin,
  2229. lvclickPosition = getLastValidPosition(clickPosition, true),
  2230. lastPosition = seekNext(lvclickPosition);
  2231. if (clickPosition < lastPosition) {
  2232. caret(input, !isMask(clickPosition, true) && !isMask(clickPosition - 1, true) ? seekNext(clickPosition) : clickPosition);
  2233. } else {
  2234. var lvp = getMaskSet().validPositions[lvclickPosition],
  2235. tt = getTestTemplate(lastPosition, lvp ? lvp.match.locator : undefined, lvp),
  2236. placeholder = getPlaceholder(lastPosition, tt.match);
  2237. if ((placeholder !== "" && getBuffer()[lastPosition] !== placeholder && tt.match.optionalQuantifier !== true && tt.match.newBlockMarker !== true) || (!isMask(lastPosition, true) && tt.match.def === placeholder)) {
  2238. var newPos = seekNext(lastPosition);
  2239. if (clickPosition >= newPos || clickPosition === lastPosition) {
  2240. lastPosition = newPos;
  2241. }
  2242. }
  2243. caret(input, lastPosition);
  2244. }
  2245. break;
  2246. }
  2247. }
  2248. }
  2249. }, 0);
  2250. },
  2251. dblclickEvent: function (e) {
  2252. var input = this;
  2253. setTimeout(function () {
  2254. caret(input, 0, seekNext(getLastValidPosition()));
  2255. }, 0);
  2256. },
  2257. cutEvent: function (e) {
  2258. var input = this,
  2259. $input = $(input),
  2260. pos = caret(input),
  2261. ev = e.originalEvent || e;
  2262. //correct clipboardData
  2263. var clipboardData = window.clipboardData || ev.clipboardData,
  2264. clipData = isRTL ? getBuffer().slice(pos.end, pos.begin) : getBuffer().slice(pos.begin, pos.end);
  2265. clipboardData.setData("text", isRTL ? clipData.reverse().join("") : clipData.join(""));
  2266. if (document.execCommand) document.execCommand("copy"); // copy selected content to system clipbaord
  2267. handleRemove(input, Inputmask.keyCode.DELETE, pos);
  2268. writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join(""));
  2269. if (input.inputmask._valueGet() === getBufferTemplate().join("")) {
  2270. $input.trigger("cleared");
  2271. }
  2272. },
  2273. blurEvent: function (e) {
  2274. var $input = $(this),
  2275. input = this;
  2276. if (input.inputmask) {
  2277. var nptValue = input.inputmask._valueGet(),
  2278. buffer = getBuffer().slice();
  2279. if (nptValue !== "") {
  2280. if (opts.clearMaskOnLostFocus) {
  2281. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  2282. buffer = [];
  2283. } else { //clearout optional tail of the mask
  2284. clearOptionalTail(buffer);
  2285. }
  2286. }
  2287. if (isComplete(buffer) === false) {
  2288. setTimeout(function () {
  2289. $input.trigger("incomplete");
  2290. }, 0);
  2291. if (opts.clearIncomplete) {
  2292. resetMaskSet();
  2293. if (opts.clearMaskOnLostFocus) {
  2294. buffer = [];
  2295. } else {
  2296. buffer = getBufferTemplate().slice();
  2297. }
  2298. }
  2299. }
  2300. writeBuffer(input, buffer, undefined, e);
  2301. }
  2302. if (undoValue !== getBuffer().join("")) {
  2303. undoValue = buffer.join("");
  2304. $input.trigger("change");
  2305. }
  2306. }
  2307. },
  2308. mouseenterEvent: function (e) {
  2309. var input = this;
  2310. mouseEnter = true;
  2311. if (document.activeElement !== input && opts.showMaskOnHover) {
  2312. if (input.inputmask._valueGet() !== getBuffer().join("")) {
  2313. writeBuffer(input, getBuffer());
  2314. }
  2315. }
  2316. },
  2317. submitEvent: function (e) { //trigger change on submit if any
  2318. if (undoValue !== getBuffer().join("")) {
  2319. $el.trigger("change");
  2320. }
  2321. if (opts.clearMaskOnLostFocus && getLastValidPosition() === -1 && el.inputmask._valueGet && el.inputmask._valueGet() === getBufferTemplate().join("")) {
  2322. el.inputmask._valueSet(""); //clear masktemplete on submit and still has focus
  2323. }
  2324. if (opts.removeMaskOnSubmit) {
  2325. el.inputmask._valueSet(el.inputmask.unmaskedvalue(), true);
  2326. setTimeout(function () {
  2327. writeBuffer(el, getBuffer());
  2328. }, 0);
  2329. }
  2330. },
  2331. resetEvent: function (e) {
  2332. el.inputmask.refreshValue = true; //indicate a forced refresh when there is a call to the value before leaving the triggering event fn
  2333. setTimeout(function () {
  2334. $el.trigger("setvalue");
  2335. }, 0);
  2336. }
  2337. };
  2338. function checkVal(input, writeOut, strict, nptvl, initiatingEvent) {
  2339. var inputValue = nptvl.slice(),
  2340. charCodes = "",
  2341. initialNdx = -1,
  2342. result = undefined;
  2343. // console.log(nptvl);
  2344. function isTemplateMatch(ndx, charCodes) {
  2345. var charCodeNdx = getBufferTemplate().slice(ndx, seekNext(ndx)).join("").indexOf(charCodes);
  2346. return charCodeNdx !== -1 && !isMask(ndx) && getTest(ndx).match.nativeDef === charCodes.charAt(charCodes.length - 1);
  2347. }
  2348. resetMaskSet();
  2349. if (!strict && opts.autoUnmask !== true) {
  2350. var staticInput = getBufferTemplate().slice(0, seekNext(-1)).join(""),
  2351. matches = inputValue.join("").match(new RegExp("^" + Inputmask.escapeRegex(staticInput), "g"));
  2352. if (matches && matches.length > 0) {
  2353. inputValue.splice(0, matches.length * staticInput.length);
  2354. initialNdx = seekNext(initialNdx);
  2355. }
  2356. } else {
  2357. initialNdx = seekNext(initialNdx);
  2358. }
  2359. if (initialNdx === -1) {
  2360. getMaskSet().p = seekNext(initialNdx);
  2361. initialNdx = 0;
  2362. } else getMaskSet().p = initialNdx;
  2363. $.each(inputValue, function (ndx, charCode) {
  2364. // console.log(charCode);
  2365. if (charCode !== undefined) { //inputfallback strips some elements out of the inputarray. $.each logically presents them as undefined
  2366. if (getMaskSet().validPositions[ndx] === undefined && inputValue[ndx] === getPlaceholder(ndx) && isMask(ndx, true) &&
  2367. isValid(ndx, inputValue[ndx], true, undefined, undefined, true) === false) {
  2368. getMaskSet().p++;
  2369. } else {
  2370. var keypress = new $.Event("_checkval");
  2371. keypress.which = charCode.charCodeAt(0);
  2372. charCodes += charCode;
  2373. var lvp = getLastValidPosition(undefined, true),
  2374. lvTest = getMaskSet().validPositions[lvp],
  2375. nextTest = getTestTemplate(lvp + 1, lvTest ? lvTest.locator.slice() : undefined, lvp);
  2376. if (!isTemplateMatch(initialNdx, charCodes) || strict || opts.autoUnmask) {
  2377. var pos = strict ? ndx : (nextTest.match.fn == null && nextTest.match.optionality && (lvp + 1) < getMaskSet().p ? lvp + 1 : getMaskSet().p);
  2378. result = EventHandlers.keypressEvent.call(input, keypress, true, false, strict, pos);
  2379. initialNdx = pos + 1;
  2380. charCodes = "";
  2381. } else {
  2382. result = EventHandlers.keypressEvent.call(input, keypress, true, false, true, lvp + 1);
  2383. }
  2384. if (result !== false && !strict && $.isFunction(opts.onBeforeWrite)) {
  2385. var origResult = result;
  2386. result = opts.onBeforeWrite.call(inputmask, keypress, getBuffer(), result.forwardPosition, opts);
  2387. result = $.extend(origResult, result);
  2388. if (result && result.refreshFromBuffer) {
  2389. var refresh = result.refreshFromBuffer;
  2390. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer);
  2391. resetMaskSet(true);
  2392. if (result.caret) {
  2393. getMaskSet().p = result.caret;
  2394. result.forwardPosition = result.caret;
  2395. }
  2396. }
  2397. }
  2398. }
  2399. }
  2400. });
  2401. if (writeOut) {
  2402. var caretPos = undefined;
  2403. if (document.activeElement === input && result) {
  2404. caretPos = opts.numericInput ? seekPrevious(result.forwardPosition) : result.forwardPosition;
  2405. }
  2406. writeBuffer(input, getBuffer(), caretPos, initiatingEvent || new $.Event("checkval"), initiatingEvent && initiatingEvent.type === "input");
  2407. }
  2408. }
  2409. function unmaskedvalue(input) {
  2410. if (input) {
  2411. if (input.inputmask === undefined) {
  2412. return input.value;
  2413. }
  2414. if (input.inputmask && input.inputmask.refreshValue) { //forced refresh from the value form.reset
  2415. EventHandlers.setValueEvent.call(input);
  2416. }
  2417. }
  2418. var umValue = [],
  2419. vps = getMaskSet().validPositions;
  2420. for (var pndx in vps) {
  2421. if (vps[pndx].match && vps[pndx].match.fn != null) {
  2422. umValue.push(vps[pndx].input);
  2423. }
  2424. }
  2425. var unmaskedValue = umValue.length === 0 ? "" : (isRTL ? umValue.reverse() : umValue).join("");
  2426. if ($.isFunction(opts.onUnMask)) {
  2427. var bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join("");
  2428. unmaskedValue = opts.onUnMask.call(inputmask, bufferValue, unmaskedValue, opts);
  2429. }
  2430. return unmaskedValue;
  2431. }
  2432. function caret(input, begin, end, notranslate) {
  2433. function translatePosition(pos) {
  2434. if (notranslate !== true && isRTL && typeof pos === "number" && (!opts.greedy || opts.placeholder !== "")) {
  2435. 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)
  2436. pos = bffrLght - pos;
  2437. }
  2438. return pos;
  2439. }
  2440. var range;
  2441. if (begin !== undefined) {
  2442. if (begin.begin !== undefined) {
  2443. end = begin.end;
  2444. begin = begin.begin;
  2445. }
  2446. if (typeof begin === "number") {
  2447. begin = translatePosition(begin);
  2448. end = translatePosition(end);
  2449. end = (typeof end == "number") ? end : begin;
  2450. // if (!$(input).is(":visible")) {
  2451. // return;
  2452. // }
  2453. var scrollCalc = parseInt(((input.ownerDocument.defaultView || window).getComputedStyle ? (input.ownerDocument.defaultView || window).getComputedStyle(input, null) : input.currentStyle).fontSize) * end;
  2454. input.scrollLeft = scrollCalc > input.scrollWidth ? scrollCalc : 0;
  2455. if (!mobile && opts.insertMode === false && begin === end) end++; //set visualization for insert/overwrite mode
  2456. if (input.setSelectionRange) {
  2457. input.selectionStart = begin;
  2458. input.selectionEnd = end;
  2459. } else if (window.getSelection) {
  2460. range = document.createRange();
  2461. if (input.firstChild === undefined || input.firstChild === null) {
  2462. var textNode = document.createTextNode("");
  2463. input.appendChild(textNode);
  2464. }
  2465. range.setStart(input.firstChild, begin < input.inputmask._valueGet().length ? begin : input.inputmask._valueGet().length);
  2466. range.setEnd(input.firstChild, end < input.inputmask._valueGet().length ? end : input.inputmask._valueGet().length);
  2467. range.collapse(true);
  2468. var sel = window.getSelection();
  2469. sel.removeAllRanges();
  2470. sel.addRange(range);
  2471. //input.focus();
  2472. } else if (input.createTextRange) {
  2473. range = input.createTextRange();
  2474. range.collapse(true);
  2475. range.moveEnd("character", end);
  2476. range.moveStart("character", begin);
  2477. range.select();
  2478. }
  2479. renderColorMask(input, {
  2480. begin: begin,
  2481. end: end
  2482. });
  2483. }
  2484. } else {
  2485. if (input.setSelectionRange) {
  2486. begin = input.selectionStart;
  2487. end = input.selectionEnd;
  2488. } else if (window.getSelection) {
  2489. range = window.getSelection().getRangeAt(0);
  2490. if (range.commonAncestorContainer.parentNode === input || range.commonAncestorContainer === input) {
  2491. begin = range.startOffset;
  2492. end = range.endOffset;
  2493. }
  2494. } else if (document.selection && document.selection.createRange) {
  2495. range = document.selection.createRange();
  2496. begin = 0 - range.duplicate().moveStart("character", -input.inputmask._valueGet().length);
  2497. end = begin + range.text.length;
  2498. }
  2499. /*eslint-disable consistent-return */
  2500. return {
  2501. "begin": translatePosition(begin),
  2502. "end": translatePosition(end)
  2503. };
  2504. /*eslint-enable consistent-return */
  2505. }
  2506. }
  2507. function determineLastRequiredPosition(returnDefinition) {
  2508. var buffer = getBuffer(),
  2509. bl = buffer.length,
  2510. pos, lvp = getLastValidPosition(),
  2511. positions = {},
  2512. lvTest = getMaskSet().validPositions[lvp],
  2513. ndxIntlzr = lvTest !== undefined ? lvTest.locator.slice() : undefined,
  2514. testPos;
  2515. for (pos = lvp + 1; pos < buffer.length; pos++) {
  2516. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  2517. ndxIntlzr = testPos.locator.slice();
  2518. positions[pos] = $.extend(true, {}, testPos);
  2519. }
  2520. var lvTestAlt = lvTest && lvTest.alternation !== undefined ? lvTest.locator[lvTest.alternation] : undefined;
  2521. for (pos = bl - 1; pos > lvp; pos--) {
  2522. testPos = positions[pos];
  2523. if ((testPos.match.optionality ||
  2524. (testPos.match.optionalQuantifier && testPos.match.newBlockMarker) ||
  2525. (lvTestAlt &&
  2526. ((lvTestAlt !== positions[pos].locator[lvTest.alternation] && testPos.match.fn != null) ||
  2527. (testPos.match.fn === null && testPos.locator[lvTest.alternation] && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAlt.toString().split(",")) && getTests(pos)[0].def !== "")))) &&
  2528. buffer[pos] === getPlaceholder(pos, testPos.match)) {
  2529. bl--;
  2530. } else break;
  2531. }
  2532. return returnDefinition ? {
  2533. "l": bl,
  2534. "def": positions[bl] ? positions[bl].match : undefined
  2535. } : bl;
  2536. }
  2537. function clearOptionalTail(buffer) {
  2538. var rl = determineLastRequiredPosition(),
  2539. validPos, bl = buffer.length;
  2540. var lv = getMaskSet().validPositions[getLastValidPosition()];
  2541. while (rl < bl &&
  2542. !isMask(rl, true) &&
  2543. (validPos = (lv !== undefined ? getTestTemplate(rl, lv.locator.slice(""), lv) : getTest(rl))) &&
  2544. validPos.match.optionality !== true &&
  2545. ((validPos.match.optionalQuantifier !== true && validPos.match.newBlockMarker !== true) || (rl + 1 === bl &&
  2546. (lv !== undefined ? getTestTemplate(rl + 1, lv.locator.slice(""), lv) : getTest(rl + 1)).match.def === ""))) {
  2547. rl++;
  2548. }
  2549. //exceptionally strip from the validatedPositions
  2550. while ((validPos = getMaskSet().validPositions[rl - 1]) && validPos && validPos.match.optionality && validPos.input === opts.skipOptionalPartCharacter) {
  2551. rl--;
  2552. }
  2553. buffer.splice(rl);
  2554. return buffer;
  2555. }
  2556. function isComplete(buffer) { //return true / false / undefined (repeat *)
  2557. if ($.isFunction(opts.isComplete)) return opts.isComplete(buffer, opts);
  2558. if (opts.repeat === "*") return undefined;
  2559. var complete = false,
  2560. lrp = determineLastRequiredPosition(true),
  2561. aml = seekPrevious(lrp.l);
  2562. if (lrp.def === undefined || lrp.def.newBlockMarker || lrp.def.optionality || lrp.def.optionalQuantifier) {
  2563. complete = true;
  2564. for (var i = 0; i <= aml; i++) {
  2565. var test = getTestTemplate(i).match;
  2566. if ((test.fn !== null && getMaskSet().validPositions[i] === undefined && test.optionality !== true && test.optionalQuantifier !== true) || (test.fn === null && buffer[i] !== getPlaceholder(i, test))) {
  2567. complete = false;
  2568. break;
  2569. }
  2570. }
  2571. }
  2572. return complete;
  2573. }
  2574. function handleRemove(input, k, pos, strict, fromIsValid) {
  2575. function generalize() {
  2576. if (opts.keepStatic) {
  2577. var validInputs = [],
  2578. lastAlt = getLastValidPosition(-1, true),
  2579. positionsClone = $.extend(true, {}, getMaskSet().validPositions),
  2580. prevAltPos = getMaskSet().validPositions[lastAlt];
  2581. //find last alternation
  2582. for (; lastAlt >= 0; lastAlt--) {
  2583. var altPos = getMaskSet().validPositions[lastAlt];
  2584. if (altPos) {
  2585. if (altPos.generatedInput !== true && /[0-9a-bA-Z]/.test(altPos.input)) {
  2586. validInputs.push(altPos.input);
  2587. }
  2588. delete getMaskSet().validPositions[lastAlt];
  2589. if (altPos.alternation !== undefined && altPos.locator[altPos.alternation] !== prevAltPos.locator[altPos.alternation]) {
  2590. break;
  2591. }
  2592. prevAltPos = altPos;
  2593. }
  2594. }
  2595. if (lastAlt > -1) {
  2596. getMaskSet().p = seekNext(getLastValidPosition(-1, true));
  2597. while (validInputs.length > 0) {
  2598. var keypress = new $.Event("keypress");
  2599. keypress.which = validInputs.pop().charCodeAt(0);
  2600. // eslint-disable-next-line no-use-before-define
  2601. EventHandlers.keypressEvent.call(input, keypress, true, false, false, getMaskSet().p);
  2602. }
  2603. } else getMaskSet().validPositions = $.extend(true, {}, positionsClone); //restore original positions
  2604. }
  2605. }
  2606. if (opts.numericInput || isRTL) {
  2607. if (k === Inputmask.keyCode.BACKSPACE) {
  2608. k = Inputmask.keyCode.DELETE;
  2609. } else if (k === Inputmask.keyCode.DELETE) {
  2610. k = Inputmask.keyCode.BACKSPACE;
  2611. }
  2612. if (isRTL) {
  2613. var pend = pos.end;
  2614. pos.end = pos.begin;
  2615. pos.begin = pend;
  2616. }
  2617. }
  2618. if (k === Inputmask.keyCode.BACKSPACE && (pos.end - pos.begin < 1 || opts.insertMode === false)) {
  2619. pos.begin = seekPrevious(pos.begin);
  2620. if (getMaskSet().validPositions[pos.begin] !== undefined && getMaskSet().validPositions[pos.begin].input === opts.groupSeparator) {
  2621. pos.begin--;
  2622. }
  2623. } else if (k === Inputmask.keyCode.DELETE && pos.begin === pos.end) {
  2624. pos.end = isMask(pos.end, true) && (getMaskSet().validPositions[pos.end] && getMaskSet().validPositions[pos.end].input !== opts.radixPoint) ?
  2625. pos.end + 1 :
  2626. seekNext(pos.end) + 1;
  2627. if (getMaskSet().validPositions[pos.begin] !== undefined && getMaskSet().validPositions[pos.begin].input === opts.groupSeparator) {
  2628. pos.end++;
  2629. }
  2630. }
  2631. stripValidPositions(pos.begin, pos.end, false, strict);
  2632. if (strict !== true) {
  2633. generalize(); //revert the alternation
  2634. }
  2635. var lvp = getLastValidPosition(pos.begin, true);
  2636. if (lvp < pos.begin) {
  2637. //if (lvp === -1) resetMaskSet();
  2638. getMaskSet().p = seekNext(lvp);
  2639. } else if (strict !== true) {
  2640. getMaskSet().p = pos.begin;
  2641. if (fromIsValid !== true) {
  2642. //put position on first valid from pos.begin ~ #1351
  2643. while (getMaskSet().p < lvp && getMaskSet().validPositions[getMaskSet().p] === undefined) {
  2644. getMaskSet().p++;
  2645. }
  2646. }
  2647. }
  2648. }
  2649. function initializeColorMask(input) {
  2650. var computedStyle = (input.ownerDocument.defaultView || window).getComputedStyle(input, null);
  2651. function findCaretPos(clientx) {
  2652. //calculate text width
  2653. var e = document.createElement("span"),
  2654. caretPos;
  2655. for (var style in computedStyle) { //clone styles
  2656. if (isNaN(style) && style.indexOf("font") !== -1) {
  2657. e.style[style] = computedStyle[style];
  2658. }
  2659. }
  2660. e.style.textTransform = computedStyle.textTransform;
  2661. e.style.letterSpacing = computedStyle.letterSpacing;
  2662. e.style.position = "absolute";
  2663. e.style.height = "auto";
  2664. e.style.width = "auto";
  2665. e.style.visibility = "hidden";
  2666. e.style.whiteSpace = "nowrap";
  2667. document.body.appendChild(e);
  2668. var inputText = input.inputmask._valueGet(),
  2669. previousWidth = 0,
  2670. itl;
  2671. for (caretPos = 0, itl = inputText.length; caretPos <= itl; caretPos++) {
  2672. e.innerHTML += inputText.charAt(caretPos) || "_";
  2673. if (e.offsetWidth >= clientx) {
  2674. var offset1 = (clientx - previousWidth);
  2675. var offset2 = e.offsetWidth - clientx;
  2676. e.innerHTML = inputText.charAt(caretPos);
  2677. offset1 -= (e.offsetWidth / 3);
  2678. caretPos = offset1 < offset2 ? caretPos - 1 : caretPos;
  2679. break;
  2680. }
  2681. previousWidth = e.offsetWidth;
  2682. }
  2683. document.body.removeChild(e);
  2684. return caretPos;
  2685. }
  2686. var template = document.createElement("div");
  2687. template.style.width = computedStyle.width;
  2688. template.style.textAlign = computedStyle.textAlign;
  2689. colorMask = document.createElement("div");
  2690. colorMask.className = "im-colormask";
  2691. input.parentNode.insertBefore(colorMask, input);
  2692. input.parentNode.removeChild(input);
  2693. colorMask.appendChild(template);
  2694. colorMask.appendChild(input);
  2695. input.style.left = template.offsetLeft + "px";
  2696. $(input).on("click", function (e) {
  2697. caret(input, findCaretPos(e.clientX));
  2698. return EventHandlers.clickEvent.call(input, [e]);
  2699. });
  2700. $(input).on("keydown", function (e) {
  2701. if (!e.shiftKey && opts.insertMode !== false) {
  2702. setTimeout(function () {
  2703. renderColorMask(input);
  2704. }, 0);
  2705. }
  2706. });
  2707. }
  2708. Inputmask.prototype.positionColorMask = function (input, template) {
  2709. input.style.left = template.offsetLeft + "px";
  2710. }
  2711. function renderColorMask(input, caretPos, clear) {
  2712. var maskTemplate = "",
  2713. isStatic = false,
  2714. test, testPos, ndxIntlzr, pos = 0;
  2715. function handleStatic() {
  2716. if (!isStatic && (test.fn === null || testPos.input === undefined)) {
  2717. isStatic = true;
  2718. maskTemplate += "<span class='im-static'>"
  2719. } else if (isStatic && ((test.fn !== null && testPos.input !== undefined) || test.def === "")) {
  2720. isStatic = false;
  2721. maskTemplate += "</span>"
  2722. }
  2723. }
  2724. function handleCaret(force) {
  2725. if ((force === true || pos === caretPos.begin) && document.activeElement === input) {
  2726. maskTemplate += "<span class='im-caret' style='border-right-width: 1px;border-right-style: solid;'></span>";
  2727. }
  2728. }
  2729. if (colorMask !== undefined) {
  2730. var buffer = getBuffer();
  2731. if (caretPos === undefined) {
  2732. caretPos = caret(input);
  2733. } else if (caretPos.begin === undefined) {
  2734. caretPos = {
  2735. begin: caretPos,
  2736. end: caretPos
  2737. };
  2738. }
  2739. if (clear !== true) {
  2740. var lvp = getLastValidPosition();
  2741. do {
  2742. handleCaret();
  2743. if (getMaskSet().validPositions[pos]) {
  2744. testPos = getMaskSet().validPositions[pos];
  2745. test = testPos.match;
  2746. ndxIntlzr = testPos.locator.slice();
  2747. handleStatic();
  2748. maskTemplate += buffer[pos];
  2749. } else {
  2750. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  2751. test = testPos.match;
  2752. ndxIntlzr = testPos.locator.slice();
  2753. if (opts.jitMasking === false || pos < lvp || (typeof opts.jitMasking === "number" && isFinite(opts.jitMasking) && opts.jitMasking > pos)) {
  2754. handleStatic();
  2755. maskTemplate += getPlaceholder(pos, test);
  2756. }
  2757. }
  2758. pos++;
  2759. } while ((maxLength === undefined || pos < maxLength) && (test.fn !== null || test.def !== "") || lvp > pos || isStatic);
  2760. if (maskTemplate.indexOf("im-caret") === -1) handleCaret(true);
  2761. if (isStatic) handleStatic();
  2762. }
  2763. var template = colorMask.getElementsByTagName("div")[0];
  2764. template.innerHTML = maskTemplate;
  2765. input.inputmask.positionColorMask(input, template);
  2766. }
  2767. }
  2768. function mask(elem) {
  2769. function isElementTypeSupported(input, opts) {
  2770. function patchValueProperty(npt) {
  2771. var valueGet;
  2772. var valueSet;
  2773. function patchValhook(type) {
  2774. if ($.valHooks && ($.valHooks[type] === undefined || $.valHooks[type].inputmaskpatch !== true)) {
  2775. var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) {
  2776. return elem.value;
  2777. };
  2778. var valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
  2779. elem.value = value;
  2780. return elem;
  2781. };
  2782. $.valHooks[type] = {
  2783. get: function (elem) {
  2784. if (elem.inputmask) {
  2785. if (elem.inputmask.opts.autoUnmask) {
  2786. return elem.inputmask.unmaskedvalue();
  2787. } else {
  2788. var result = valhookGet(elem);
  2789. return getLastValidPosition(undefined, undefined, elem.inputmask.maskset.validPositions) !== -1 || opts.nullable !== true ? result : "";
  2790. }
  2791. } else return valhookGet(elem);
  2792. },
  2793. set: function (elem, value) {
  2794. var $elem = $(elem),
  2795. result;
  2796. result = valhookSet(elem, value);
  2797. if (elem.inputmask) {
  2798. $elem.trigger("setvalue");
  2799. }
  2800. return result;
  2801. },
  2802. inputmaskpatch: true
  2803. };
  2804. }
  2805. }
  2806. function getter() {
  2807. if (this.inputmask) {
  2808. return this.inputmask.opts.autoUnmask ?
  2809. this.inputmask.unmaskedvalue() :
  2810. (getLastValidPosition() !== -1 || opts.nullable !== true ?
  2811. (document.activeElement === this && opts.clearMaskOnLostFocus ?
  2812. (isRTL ? clearOptionalTail(getBuffer().slice()).reverse() : clearOptionalTail(getBuffer().slice())).join("") :
  2813. valueGet.call(this)) :
  2814. "");
  2815. } else return valueGet.call(this);
  2816. }
  2817. function setter(value) {
  2818. valueSet.call(this, value);
  2819. if (this.inputmask) {
  2820. $(this).trigger("setvalue");
  2821. }
  2822. }
  2823. function installNativeValueSetFallback(npt) {
  2824. EventRuler.on(npt, "mouseenter", function (event) {
  2825. var $input = $(this),
  2826. input = this,
  2827. value = input.inputmask._valueGet();
  2828. if (value !== getBuffer().join("") /*&& getLastValidPosition() > 0*/ ) {
  2829. $input.trigger("setvalue");
  2830. }
  2831. });
  2832. }
  2833. if (!npt.inputmask.__valueGet) {
  2834. if (opts.noValuePatching !== true) {
  2835. if (Object.getOwnPropertyDescriptor) {
  2836. if (typeof Object.getPrototypeOf !== "function") {
  2837. Object.getPrototypeOf = typeof "test".__proto__ === "object" ? function (object) {
  2838. return object.__proto__;
  2839. } : function (object) {
  2840. return object.constructor.prototype;
  2841. };
  2842. }
  2843. var valueProperty = Object.getPrototypeOf ? Object.getOwnPropertyDescriptor(Object.getPrototypeOf(npt), "value") : undefined;
  2844. if (valueProperty && valueProperty.get && valueProperty.set) {
  2845. valueGet = valueProperty.get;
  2846. valueSet = valueProperty.set;
  2847. Object.defineProperty(npt, "value", {
  2848. get: getter,
  2849. set: setter,
  2850. configurable: true
  2851. });
  2852. } else if (npt.tagName !== "INPUT") {
  2853. valueGet = function () {
  2854. return this.textContent;
  2855. };
  2856. valueSet = function (value) {
  2857. this.textContent = value;
  2858. };
  2859. Object.defineProperty(npt, "value", {
  2860. get: getter,
  2861. set: setter,
  2862. configurable: true
  2863. });
  2864. }
  2865. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  2866. valueGet = npt.__lookupGetter__("value");
  2867. valueSet = npt.__lookupSetter__("value");
  2868. npt.__defineGetter__("value", getter);
  2869. npt.__defineSetter__("value", setter);
  2870. }
  2871. npt.inputmask.__valueGet = valueGet; //store native property getter
  2872. npt.inputmask.__valueSet = valueSet; //store native property setter
  2873. }
  2874. npt.inputmask._valueGet = function (overruleRTL) {
  2875. return isRTL && overruleRTL !== true ? valueGet.call(this.el).split("").reverse().join("") : valueGet.call(this.el);
  2876. };
  2877. npt.inputmask._valueSet = function (value, overruleRTL) { //null check is needed for IE8 => otherwise converts to "null"
  2878. valueSet.call(this.el, (value === null || value === undefined) ? "" : ((overruleRTL !== true && isRTL) ? value.split("").reverse().join("") : value));
  2879. };
  2880. if (valueGet === undefined) { //jquery.val fallback
  2881. valueGet = function () {
  2882. return this.value;
  2883. };
  2884. valueSet = function (value) {
  2885. this.value = value;
  2886. };
  2887. patchValhook(npt.type);
  2888. installNativeValueSetFallback(npt);
  2889. }
  2890. }
  2891. }
  2892. var elementType = input.getAttribute("type");
  2893. var isSupported = (input.tagName === "INPUT" && $.inArray(elementType, opts.supportsInputType) !== -1) || input.isContentEditable || input.tagName === "TEXTAREA";
  2894. if (!isSupported) {
  2895. if (input.tagName === "INPUT") {
  2896. var el = document.createElement("input");
  2897. el.setAttribute("type", elementType);
  2898. isSupported = el.type === "text"; //apply mask only if the type is not natively supported
  2899. el = null;
  2900. } else isSupported = "partial";
  2901. }
  2902. if (isSupported !== false) {
  2903. patchValueProperty(input);
  2904. } else input.inputmask = undefined;
  2905. return isSupported;
  2906. }
  2907. //unbind all events - to make sure that no other mask will interfere when re-masking
  2908. EventRuler.off(elem);
  2909. var isSupported = isElementTypeSupported(elem, opts);
  2910. if (isSupported !== false) {
  2911. el = elem;
  2912. $el = $(el);
  2913. //read maxlength prop from el
  2914. maxLength = el !== undefined ? el.maxLength : undefined;
  2915. if (maxLength === -1) maxLength = undefined;
  2916. if (opts.colorMask === true) {
  2917. initializeColorMask(el);
  2918. }
  2919. if (android) {
  2920. if (el.hasOwnProperty("inputmode")) {
  2921. el.inputmode = opts.inputmode;
  2922. el.setAttribute("inputmode", opts.inputmode);
  2923. }
  2924. if (opts.androidHack === "rtfm") {
  2925. if (opts.colorMask !== true) {
  2926. initializeColorMask(el);
  2927. }
  2928. el.type = "password";
  2929. }
  2930. }
  2931. if (isSupported === true) {
  2932. //bind events
  2933. EventRuler.on(el, "submit", EventHandlers.submitEvent);
  2934. EventRuler.on(el, "reset", EventHandlers.resetEvent);
  2935. EventRuler.on(el, "mouseenter", EventHandlers.mouseenterEvent);
  2936. EventRuler.on(el, "blur", EventHandlers.blurEvent);
  2937. EventRuler.on(el, "focus", EventHandlers.focusEvent);
  2938. EventRuler.on(el, "mouseleave", EventHandlers.mouseleaveEvent);
  2939. if (opts.colorMask !== true) {
  2940. EventRuler.on(el, "click", EventHandlers.clickEvent);
  2941. }
  2942. EventRuler.on(el, "dblclick", EventHandlers.dblclickEvent);
  2943. EventRuler.on(el, "paste", EventHandlers.pasteEvent);
  2944. EventRuler.on(el, "dragdrop", EventHandlers.pasteEvent);
  2945. EventRuler.on(el, "drop", EventHandlers.pasteEvent);
  2946. EventRuler.on(el, "cut", EventHandlers.cutEvent);
  2947. EventRuler.on(el, "complete", opts.oncomplete);
  2948. EventRuler.on(el, "incomplete", opts.onincomplete);
  2949. EventRuler.on(el, "cleared", opts.oncleared);
  2950. if (!android && opts.inputEventOnly !== true) {
  2951. EventRuler.on(el, "keydown", EventHandlers.keydownEvent);
  2952. EventRuler.on(el, "keypress", EventHandlers.keypressEvent);
  2953. } else el.removeAttribute("maxLength");
  2954. EventRuler.on(el, "compositionstart", $.noop);
  2955. EventRuler.on(el, "compositionupdate", $.noop);
  2956. EventRuler.on(el, "compositionend", $.noop);
  2957. EventRuler.on(el, "keyup", $.noop);
  2958. EventRuler.on(el, "input", EventHandlers.inputFallBackEvent);
  2959. EventRuler.on(el, "beforeinput", $.noop); //https://github.com/w3c/input-events - to implement
  2960. }
  2961. EventRuler.on(el, "setvalue", EventHandlers.setValueEvent);
  2962. //apply mask
  2963. undoValue = getBufferTemplate().join(""); //initialize the buffer and getmasklength
  2964. if (el.inputmask._valueGet(true) !== "" || opts.clearMaskOnLostFocus === false || document.activeElement === el) {
  2965. var initialValue = $.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call(inputmask, el.inputmask._valueGet(true), opts) || el.inputmask._valueGet(true)) : el.inputmask._valueGet(true);
  2966. if (initialValue !== "") checkVal(el, true, false, isRTL ? initialValue.split("").reverse() : initialValue.split(""));
  2967. var buffer = getBuffer().slice();
  2968. undoValue = buffer.join("");
  2969. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  2970. if (isComplete(buffer) === false) {
  2971. if (opts.clearIncomplete) {
  2972. resetMaskSet();
  2973. }
  2974. }
  2975. if (opts.clearMaskOnLostFocus && document.activeElement !== el) {
  2976. if (getLastValidPosition() === -1) {
  2977. buffer = [];
  2978. } else {
  2979. clearOptionalTail(buffer);
  2980. }
  2981. }
  2982. writeBuffer(el, buffer);
  2983. if (document.activeElement === el) { //position the caret when in focus
  2984. caret(el, seekNext(getLastValidPosition()));
  2985. }
  2986. }
  2987. }
  2988. }
  2989. //action object
  2990. var valueBuffer;
  2991. if (actionObj !== undefined) {
  2992. switch (actionObj.action) {
  2993. case "isComplete":
  2994. el = actionObj.el;
  2995. return isComplete(getBuffer());
  2996. case "unmaskedvalue":
  2997. if (el === undefined || actionObj.value !== undefined) {
  2998. valueBuffer = actionObj.value;
  2999. valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call(inputmask, valueBuffer, opts) || valueBuffer) : valueBuffer).split("");
  3000. checkVal(undefined, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  3001. if ($.isFunction(opts.onBeforeWrite)) opts.onBeforeWrite.call(inputmask, undefined, getBuffer(), 0, opts);
  3002. }
  3003. return unmaskedvalue(el);
  3004. case "mask":
  3005. mask(el);
  3006. break;
  3007. case "format":
  3008. valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call(inputmask, actionObj.value, opts) || actionObj.value) : actionObj.value).split("");
  3009. checkVal(undefined, true, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  3010. if (actionObj.metadata) {
  3011. return {
  3012. value: isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join(""),
  3013. metadata: maskScope.call(this, {
  3014. "action": "getmetadata"
  3015. }, maskset, opts)
  3016. };
  3017. }
  3018. return isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join("");
  3019. case "isValid":
  3020. if (actionObj.value) {
  3021. valueBuffer = actionObj.value.split("");
  3022. checkVal(undefined, true, true, isRTL ? valueBuffer.reverse() : valueBuffer);
  3023. } else {
  3024. actionObj.value = getBuffer().join("");
  3025. }
  3026. var buffer = getBuffer();
  3027. var rl = determineLastRequiredPosition(),
  3028. lmib = buffer.length - 1;
  3029. for (; lmib > rl; lmib--) {
  3030. if (isMask(lmib)) break;
  3031. }
  3032. buffer.splice(rl, lmib + 1 - rl);
  3033. return isComplete(buffer) && actionObj.value === getBuffer().join("");
  3034. case "getemptymask":
  3035. return getBufferTemplate().join("");
  3036. case "remove":
  3037. if (el && el.inputmask) {
  3038. $el = $(el);
  3039. //writeout the value
  3040. el.inputmask._valueSet(opts.autoUnmask ? unmaskedvalue(el) : el.inputmask._valueGet(true));
  3041. //unbind all events
  3042. EventRuler.off(el);
  3043. //restore the value property
  3044. var valueProperty;
  3045. if (Object.getOwnPropertyDescriptor && Object.getPrototypeOf) {
  3046. valueProperty = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el), "value");
  3047. if (valueProperty) {
  3048. if (el.inputmask.__valueGet) {
  3049. Object.defineProperty(el, "value", {
  3050. get: el.inputmask.__valueGet,
  3051. set: el.inputmask.__valueSet,
  3052. configurable: true
  3053. });
  3054. }
  3055. }
  3056. } else if (document.__lookupGetter__ && el.__lookupGetter__("value")) {
  3057. if (el.inputmask.__valueGet) {
  3058. el.__defineGetter__("value", el.inputmask.__valueGet);
  3059. el.__defineSetter__("value", el.inputmask.__valueSet);
  3060. }
  3061. }
  3062. //clear data
  3063. el.inputmask = undefined;
  3064. }
  3065. return el;
  3066. break;
  3067. case "getmetadata":
  3068. if ($.isArray(maskset.metadata)) {
  3069. var maskTarget = getMaskTemplate(true, 0, false).join("");
  3070. $.each(maskset.metadata, function (ndx, mtdt) {
  3071. if (mtdt.mask === maskTarget) {
  3072. maskTarget = mtdt;
  3073. return false;
  3074. }
  3075. });
  3076. return maskTarget;
  3077. }
  3078. return maskset.metadata;
  3079. }
  3080. }
  3081. }
  3082. //make inputmask available
  3083. return Inputmask;
  3084. }));