inputmask.js 104 KB

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