inputmask.js 113 KB

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