inputmask.js 99 KB

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