inputmask.js 186 KB

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