inputmask.js 94 KB

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