inputmask.js 103 KB

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