inputmask.js 185 KB

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