inputmask.js 100 KB

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