inputmask.js 103 KB

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