inputmask.js 95 KB

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