inputmask.js 102 KB

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