inputmask.js 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638
  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. }
  585. } else masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[mask]);
  586. return masksetDefinition;
  587. }
  588. }
  589. function preProcessMask(mask) {
  590. mask = mask.toString();
  591. // if (opts.numericInput) {
  592. // mask = mask.split('').reverse();
  593. // mask = mask.join('');
  594. // }
  595. return mask;
  596. }
  597. if ($.isFunction(opts.mask)) { //allow mask to be a preprocessing fn - should return a valid mask
  598. opts.mask = opts.mask.call(this, opts);
  599. }
  600. if ($.isArray(opts.mask)) {
  601. if (opts.mask.length > 1) {
  602. opts.keepStatic = opts.keepStatic === undefined ? true : opts.keepStatic; //enable by default when passing multiple masks when the option is not explicitly specified
  603. var altMask = "(";
  604. $.each(opts.numericInput ? opts.mask.reverse() : opts.mask, function(ndx, msk) {
  605. if (altMask.length > 1) {
  606. altMask += ")|(";
  607. }
  608. if (msk.mask !== undefined && !$.isFunction(msk.mask)) {
  609. altMask += preProcessMask(msk.mask);
  610. } else {
  611. altMask += preProcessMask(msk);
  612. }
  613. });
  614. altMask += ")";
  615. return generateMask(altMask, opts.mask);
  616. } else opts.mask = opts.mask.pop();
  617. }
  618. if (opts.mask) {
  619. if (opts.mask.mask !== undefined && !$.isFunction(opts.mask.mask)) {
  620. ms = generateMask(preProcessMask(opts.mask.mask), opts.mask);
  621. } else {
  622. ms = generateMask(preProcessMask(opts.mask), opts.mask);
  623. }
  624. }
  625. return ms;
  626. }
  627. var ua = navigator.userAgent,
  628. iphone = ua.match(new RegExp("iphone", "i")) !== null,
  629. // android = ua.match(new RegExp("android.*safari.*", "i")) !== null,
  630. androidchrome = ua.match(new RegExp("android.*chrome.*", "i")) !== null,
  631. androidfirefox = ua.match(new RegExp("android.*firefox.*", "i")) !== null,
  632. // 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),
  633. PasteEventType = isInputEventSupported("paste") ? "paste" : isInputEventSupported("input") ? "input" : "propertychange";
  634. //if (androidchrome) {
  635. // var browser = navigator.userAgent.match(new RegExp("chrome.*", "i")),
  636. // version = parseInt(new RegExp(/[0-9]+/).exec(browser));
  637. // androidchrome32 = (version == 32);
  638. //}
  639. //masking scope
  640. //actionObj definition see below
  641. function maskScope(actionObj, maskset, opts) {
  642. var isRTL = false,
  643. undoValue,
  644. // compositionValidPos,
  645. compositionCaretPos,
  646. compositionData,
  647. el, $el,
  648. skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
  649. skipInputEvent = false, //skip when triggered from within inputmask
  650. ignorable = false,
  651. maxLength,
  652. mouseEnter = true;
  653. //maskset helperfunctions
  654. function getMaskTemplate(baseOnInput, minimalPos, includeInput) {
  655. minimalPos = minimalPos || 0;
  656. var maskTemplate = [],
  657. ndxIntlzr, pos = 0,
  658. test, testPos;
  659. do {
  660. if (baseOnInput === true && getMaskSet().validPositions[pos]) {
  661. var validPos = getMaskSet().validPositions[pos];
  662. test = validPos.match;
  663. ndxIntlzr = validPos.locator.slice();
  664. maskTemplate.push(includeInput === true ? validPos.input : getPlaceholder(pos, test));
  665. } else {
  666. //console.log("getmasktemplate " + pos + " " + JSON.stringify(ndxIntlzr));
  667. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  668. test = testPos.match;
  669. ndxIntlzr = testPos.locator.slice();
  670. maskTemplate.push(getPlaceholder(pos, test));
  671. }
  672. pos++;
  673. } while ((maxLength === undefined || pos - 1 < maxLength) && test.fn !== null || (test.fn === null && test.def !== "") || minimalPos >= pos);
  674. maskTemplate.pop(); //drop the last one which is empty
  675. return maskTemplate;
  676. }
  677. function getMaskSet() {
  678. return maskset;
  679. }
  680. function resetMaskSet(soft) {
  681. var maskset = getMaskSet();
  682. maskset.buffer = undefined;
  683. maskset.tests = {};
  684. if (soft !== true) {
  685. maskset._buffer = undefined;
  686. maskset.validPositions = {};
  687. maskset.p = 0;
  688. }
  689. }
  690. function getLastValidPosition(closestTo, strict) {
  691. var maskset = getMaskSet(),
  692. lastValidPosition = -1,
  693. valids = maskset.validPositions;
  694. if (closestTo === undefined) closestTo = -1;
  695. var before = lastValidPosition,
  696. after = lastValidPosition;
  697. for (var posNdx in valids) {
  698. var psNdx = parseInt(posNdx);
  699. if (valids[psNdx] && (strict || valids[psNdx].match.fn !== null)) {
  700. if (psNdx <= closestTo) before = psNdx;
  701. if (psNdx >= closestTo) after = psNdx;
  702. }
  703. }
  704. lastValidPosition = (before !== -1 && (closestTo - before) > 1) || after < closestTo ? before : after;
  705. return lastValidPosition;
  706. }
  707. function setValidPosition(pos, validTest, fromSetValid) {
  708. if (opts.insertMode && getMaskSet().validPositions[pos] !== undefined && fromSetValid === undefined) {
  709. //reposition & revalidate others
  710. var positionsClone = $.extend(true, {}, getMaskSet().validPositions),
  711. lvp = getLastValidPosition(),
  712. i;
  713. for (i = pos; i <= lvp; i++) { //clear selection
  714. delete getMaskSet().validPositions[i];
  715. }
  716. getMaskSet().validPositions[pos] = validTest;
  717. var valid = true,
  718. j, vps = getMaskSet().validPositions;
  719. for (i = (j = pos); i <= lvp; i++) {
  720. var t = positionsClone[i];
  721. if (t !== undefined) {
  722. var posMatch = j,
  723. prevPosMatch = -1;
  724. while (posMatch < getMaskLength() && ((t.match.fn == null && vps[i] && (vps[i].match.optionalQuantifier === true || vps[i].match.optionality === true)) || t.match.fn != null)) {
  725. //determine next position
  726. 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))) {
  727. posMatch++;
  728. } else posMatch = seekNext(j);
  729. //does it match
  730. if (positionCanMatchDefinition(posMatch, t.match.def)) {
  731. valid = isValid(posMatch, t.input, true, true) !== false;
  732. j = posMatch;
  733. break;
  734. } else {
  735. valid = t.match.fn == null;
  736. if (prevPosMatch === posMatch) break; //prevent endless loop
  737. prevPosMatch = posMatch;
  738. }
  739. }
  740. }
  741. if (!valid) break;
  742. }
  743. if (!valid) {
  744. getMaskSet().validPositions = $.extend(true, {}, positionsClone);
  745. return false;
  746. }
  747. } else 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. for (i = startPos; i < end; i++) { //clear selection
  754. if (getMaskSet().validPositions[i] !== undefined) {
  755. if (nocheck === true || opts.canClearPosition(getMaskSet(), i, getLastValidPosition(), strict, opts) !== false) {
  756. delete getMaskSet().validPositions[i];
  757. }
  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. }
  781. for (i = lvp + 1; i <= ml; i++) {
  782. if (getMaskSet().validPositions[i]) {
  783. delete getMaskSet().validPositions[i];
  784. }
  785. }
  786. resetMaskSet(true);
  787. }
  788. function getTestTemplate(pos, ndxIntlzr, tstPs) {
  789. var testPos = getMaskSet().validPositions[pos];
  790. if (testPos === undefined) {
  791. var testPositions = getTests(pos, ndxIntlzr, tstPs),
  792. lvp = getLastValidPosition(),
  793. lvTest = getMaskSet().validPositions[lvp] || getTests(0)[0],
  794. lvTestAltArr = (lvTest.alternation !== undefined) ? lvTest.locator[lvTest.alternation].toString().split(",") : [];
  795. for (var ndx = 0; ndx < testPositions.length; ndx++) {
  796. testPos = testPositions[ndx];
  797. if (testPos.match &&
  798. (((opts.greedy && testPos.match.optionalQuantifier !== true) || (testPos.match.optionality === false || testPos.match.newBlockMarker === false) && testPos.match.optionalQuantifier !== true) &&
  799. ((lvTest.alternation === undefined || lvTest.alternation !== testPos.alternation) ||
  800. (testPos.locator[lvTest.alternation] !== undefined && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAltArr))))) {
  801. break;
  802. }
  803. }
  804. }
  805. return testPos;
  806. }
  807. function getTest(pos) {
  808. if (getMaskSet().validPositions[pos]) {
  809. return getMaskSet().validPositions[pos].match;
  810. }
  811. return getTests(pos)[0].match;
  812. }
  813. function positionCanMatchDefinition(pos, def) {
  814. var valid = false,
  815. tests = getTests(pos);
  816. for (var tndx = 0; tndx < tests.length; tndx++) {
  817. if (tests[tndx].match && tests[tndx].match.def === def) {
  818. valid = true;
  819. break;
  820. }
  821. }
  822. return valid;
  823. }
  824. function getTests(pos, ndxIntlzr, tstPs, cacheable) {
  825. var maskTokens = getMaskSet().maskToken,
  826. testPos = ndxIntlzr ? tstPs : 0,
  827. ndxInitializer = ndxIntlzr || [0],
  828. matches = [],
  829. insertStop = false,
  830. latestMatch, isFirstMatch;
  831. function resolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) { //ndxInitilizer contains a set of indexes to speedup searches in the mtokens
  832. function handleMatch(match, loopNdx, quantifierRecurse) {
  833. if (testPos > 10000) {
  834. 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);
  835. return true;
  836. }
  837. if (testPos === pos && match.matches === undefined) {
  838. matches.push({
  839. "match": match,
  840. "locator": loopNdx.reverse()
  841. });
  842. return true;
  843. } else if (match.matches !== undefined) {
  844. if (match.isGroup && quantifierRecurse !== match) { //when a group pass along to the quantifier
  845. match = handleMatch(maskToken.matches[$.inArray(match, maskToken.matches) + 1], loopNdx);
  846. if (match) return true;
  847. } else if (match.isOptional) {
  848. var optionalToken = match;
  849. match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  850. if (match) {
  851. latestMatch = matches[matches.length - 1].match;
  852. isFirstMatch = $.inArray(latestMatch, optionalToken.matches) === 0;
  853. if (isFirstMatch) {
  854. insertStop = true; //insert a stop
  855. testPos = pos; //match the position after the group
  856. } else return true;
  857. }
  858. } else if (match.isAlternator) {
  859. var alternateToken = match,
  860. malternateMatches = [],
  861. maltMatches,
  862. currentMatches = matches.slice(),
  863. loopNdxCnt = loopNdx.length;
  864. var altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1;
  865. if (altIndex === -1 || typeof altIndex === "string") {
  866. var currentPos = testPos,
  867. ndxInitializerClone = ndxInitializer.slice(),
  868. altIndexArr = [];
  869. if (typeof altIndex == "string") altIndexArr = altIndex.split(",");
  870. for (var amndx = 0; amndx < alternateToken.matches.length; amndx++) {
  871. matches = [];
  872. match = handleMatch(alternateToken.matches[amndx], [amndx].concat(loopNdx), quantifierRecurse) || match;
  873. if (match !== true && match !== undefined && (altIndexArr[altIndexArr.length - 1] < alternateToken.matches.length)) { //no match in the alternations (length mismatch) => look further
  874. var ntndx = maskToken.matches.indexOf(match) + 1;
  875. if (maskToken.matches.length > ntndx) {
  876. match = handleMatch(maskToken.matches[ntndx], [ntndx].concat(loopNdx.slice(1, loopNdx.length)), quantifierRecurse);
  877. if (match) {
  878. altIndexArr.push(ntndx.toString());
  879. $.each(matches, function(ndx, lmnt) {
  880. lmnt.alternation = loopNdx.length - 1;
  881. });
  882. }
  883. }
  884. }
  885. maltMatches = matches.slice();
  886. testPos = currentPos;
  887. matches = [];
  888. //cloneback
  889. for (var i = 0; i < ndxInitializerClone.length; i++) {
  890. ndxInitializer[i] = ndxInitializerClone[i];
  891. }
  892. //fuzzy merge matches
  893. for (var ndx1 = 0; ndx1 < maltMatches.length; ndx1++) {
  894. var altMatch = maltMatches[ndx1];
  895. altMatch.alternation = altMatch.alternation || loopNdxCnt;
  896. for (var ndx2 = 0; ndx2 < malternateMatches.length; ndx2++) {
  897. var altMatch2 = malternateMatches[ndx2];
  898. //verify equality
  899. if (altMatch.match.mask === altMatch2.match.mask && (typeof altIndex !== "string" || $.inArray(altMatch.locator[altMatch.alternation].toString(), altIndexArr) !== -1)) {
  900. maltMatches.splice(ndx1, 1);
  901. ndx1--;
  902. altMatch2.locator[altMatch.alternation] = altMatch2.locator[altMatch.alternation] + "," + altMatch.locator[altMatch.alternation];
  903. altMatch2.alternation = altMatch.alternation; //we pass the alternation index => used in determineLastRequiredPosition
  904. break;
  905. }
  906. }
  907. }
  908. malternateMatches = malternateMatches.concat(maltMatches);
  909. }
  910. if (typeof altIndex == "string") { //filter matches
  911. malternateMatches = $.map(malternateMatches, function(lmnt, ndx) {
  912. if (isFinite(ndx)) {
  913. var mamatch,
  914. alternation = lmnt.alternation,
  915. altLocArr = lmnt.locator[alternation].toString().split(",");
  916. lmnt.locator[alternation] = undefined;
  917. lmnt.alternation = undefined;
  918. for (var alndx = 0; alndx < altLocArr.length; alndx++) {
  919. mamatch = $.inArray(altLocArr[alndx], altIndexArr) !== -1;
  920. if (mamatch) { //rebuild the locator with valid entries
  921. if (lmnt.locator[alternation] !== undefined) {
  922. lmnt.locator[alternation] += ",";
  923. lmnt.locator[alternation] += altLocArr[alndx];
  924. } else lmnt.locator[alternation] = parseInt(altLocArr[alndx]);
  925. lmnt.alternation = alternation;
  926. }
  927. }
  928. if (lmnt.locator[alternation] !== undefined) return lmnt;
  929. }
  930. });
  931. }
  932. matches = currentMatches.concat(malternateMatches);
  933. testPos = pos;
  934. insertStop = matches.length > 0; //insert a stopelemnt when there is an alternate
  935. } else {
  936. if (alternateToken.matches[altIndex]) { //if not in the initial alternation => look further
  937. match = handleMatch(alternateToken.matches[altIndex], [altIndex].concat(loopNdx), quantifierRecurse);
  938. } else match = false;
  939. }
  940. if (match) return true;
  941. } else if (match.isQuantifier && quantifierRecurse !== maskToken.matches[$.inArray(match, maskToken.matches) - 1]) {
  942. var qt = match;
  943. for (var qndx = (ndxInitializer.length > 0) ? ndxInitializer.shift() : 0;
  944. (qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max)) && testPos <= pos; qndx++) {
  945. var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1];
  946. match = handleMatch(tokenGroup, [qndx].concat(loopNdx), tokenGroup); //set the tokenGroup as quantifierRecurse marker
  947. if (match) {
  948. //get latest match
  949. latestMatch = matches[matches.length - 1].match;
  950. latestMatch.optionalQuantifier = qndx > (qt.quantifier.min - 1);
  951. isFirstMatch = $.inArray(latestMatch, tokenGroup.matches) === 0;
  952. if (isFirstMatch) { //search for next possible match
  953. if (qndx > (qt.quantifier.min - 1)) {
  954. insertStop = true;
  955. testPos = pos; //match the position after the group
  956. break; //stop quantifierloop
  957. } else return true;
  958. } else {
  959. return true;
  960. }
  961. }
  962. }
  963. } else {
  964. match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  965. if (match) 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. }
  990. previousPos--;
  991. }
  992. if (test !== undefined && previousPos > -1) {
  993. testPos = previousPos;
  994. ndxInitializer = test.locator.slice();
  995. }
  996. }
  997. for (var mtndx = ndxInitializer.shift(); mtndx < maskTokens.length; mtndx++) {
  998. var match = resolveTestFromToken(maskTokens[mtndx], ndxInitializer, [mtndx]);
  999. if ((match && testPos === pos) || testPos > pos) {
  1000. break;
  1001. }
  1002. }
  1003. if (matches.length === 0 || insertStop) {
  1004. matches.push({
  1005. "match": {
  1006. fn: null,
  1007. cardinality: 0,
  1008. optionality: true,
  1009. casing: null,
  1010. def: ""
  1011. },
  1012. "locator": []
  1013. });
  1014. }
  1015. getMaskSet().tests[pos] = $.extend(true, [], matches); //set a clone to prevent overwriting some props
  1016. // console.log(pos + " - " + JSON.stringify(matches));
  1017. return getMaskSet().tests[pos];
  1018. }
  1019. function getBufferTemplate() {
  1020. if (getMaskSet()._buffer === undefined) {
  1021. //generate template
  1022. getMaskSet()._buffer = getMaskTemplate(false, 1);
  1023. }
  1024. return getMaskSet()._buffer;
  1025. }
  1026. function getBuffer() {
  1027. if (getMaskSet().buffer === undefined) {
  1028. getMaskSet().buffer = getMaskTemplate(true, getLastValidPosition(), true);
  1029. }
  1030. return getMaskSet().buffer;
  1031. }
  1032. function refreshFromBuffer(start, end, buffer) {
  1033. var i;
  1034. buffer = buffer || getBuffer().slice(); //pass or work on clone
  1035. if (start === true) {
  1036. resetMaskSet();
  1037. start = 0;
  1038. end = buffer.length;
  1039. } else {
  1040. for (i = start; i < end; i++) {
  1041. delete getMaskSet().validPositions[i];
  1042. delete getMaskSet().tests[i];
  1043. }
  1044. }
  1045. for (i = start; i < end; i++) {
  1046. if (buffer[i] !== opts.skipOptionalPartCharacter) {
  1047. isValid(i, buffer[i], true, true);
  1048. }
  1049. }
  1050. }
  1051. function casing(elem, test) {
  1052. switch (test.casing) {
  1053. case "upper":
  1054. elem = elem.toUpperCase();
  1055. break;
  1056. case "lower":
  1057. elem = elem.toLowerCase();
  1058. break;
  1059. }
  1060. return elem;
  1061. }
  1062. function checkAlternationMatch(altArr1, altArr2) {
  1063. var altArrC = opts.greedy ? altArr2 : altArr2.slice(0, 1),
  1064. isMatch = false;
  1065. for (var alndx = 0; alndx < altArr1.length; alndx++) {
  1066. if ($.inArray(altArr1[alndx], altArrC) !== -1) {
  1067. isMatch = true;
  1068. break;
  1069. }
  1070. }
  1071. return isMatch;
  1072. }
  1073. function isValid(pos, c, strict, fromSetValid) { //strict true ~ no correction or autofill
  1074. strict = strict === true; //always set a value to strict to prevent possible strange behavior in the extensions
  1075. function _isValid(position, c, strict, fromSetValid) {
  1076. var rslt = false;
  1077. //console.log(JSON.stringify(getTests(position)));
  1078. $.each(getTests(position), function(ndx, tst) {
  1079. var test = tst.match;
  1080. var loopend = c ? 1 : 0,
  1081. chrs = "";
  1082. for (var i = test.cardinality; i > loopend; i--) {
  1083. chrs += getBufferElement(position - (i - 1));
  1084. }
  1085. if (c) {
  1086. chrs += c;
  1087. }
  1088. //return is false or a json object => { pos: ??, c: ??} or true
  1089. rslt = test.fn != null ?
  1090. test.fn.test(chrs, getMaskSet(), position, strict, opts) : (c === test.def || c === opts.skipOptionalPartCharacter) && test.def !== "" ? //non mask
  1091. {
  1092. c: test.def,
  1093. pos: position
  1094. } : false;
  1095. if (rslt !== false) {
  1096. var elem = rslt.c !== undefined ? rslt.c : c;
  1097. elem = (elem === opts.skipOptionalPartCharacter && test.fn === null) ? test.def : elem;
  1098. var validatedPos = position,
  1099. possibleModifiedBuffer = getBuffer();
  1100. if (rslt.remove !== undefined) { //remove position(s)
  1101. if (!$.isArray(rslt.remove)) rslt.remove = [rslt.remove];
  1102. $.each(rslt.remove.sort(function(a, b) {
  1103. return b - a;
  1104. }), function(ndx, lmnt) {
  1105. stripValidPositions(lmnt, lmnt + 1, true);
  1106. });
  1107. }
  1108. if (rslt.insert !== undefined) { //insert position(s)
  1109. if (!$.isArray(rslt.insert)) rslt.insert = [rslt.insert];
  1110. $.each(rslt.insert.sort(function(a, b) {
  1111. return a - b;
  1112. }), function(ndx, lmnt) {
  1113. isValid(lmnt.pos, lmnt.c, true);
  1114. });
  1115. }
  1116. if (rslt.refreshFromBuffer) {
  1117. var refresh = rslt.refreshFromBuffer;
  1118. strict = true;
  1119. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, possibleModifiedBuffer);
  1120. if (rslt.pos === undefined && rslt.c === undefined) {
  1121. rslt.pos = getLastValidPosition();
  1122. return false; //breakout if refreshFromBuffer && nothing to insert
  1123. }
  1124. validatedPos = rslt.pos !== undefined ? rslt.pos : position;
  1125. if (validatedPos !== position) {
  1126. rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
  1127. return false;
  1128. }
  1129. } else if (rslt !== true && rslt.pos !== undefined && rslt.pos !== position) { //their is a position offset
  1130. validatedPos = rslt.pos;
  1131. refreshFromBuffer(position, validatedPos);
  1132. if (validatedPos !== position) {
  1133. rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
  1134. return false;
  1135. }
  1136. }
  1137. if (rslt !== true && rslt.pos === undefined && rslt.c === undefined) {
  1138. return false; //breakout if nothing to insert
  1139. }
  1140. if (ndx > 0) {
  1141. resetMaskSet(true);
  1142. }
  1143. if (!setValidPosition(validatedPos, $.extend({}, tst, {
  1144. "input": casing(elem, test)
  1145. }), fromSetValid)) {
  1146. rslt = false;
  1147. }
  1148. return false; //break from $.each
  1149. }
  1150. });
  1151. return rslt;
  1152. }
  1153. function alternate(pos, c, strict, fromSetValid) {
  1154. var validPsClone = $.extend(true, {}, getMaskSet().validPositions),
  1155. lastAlt,
  1156. alternation,
  1157. isValidRslt,
  1158. altPos, i, validPos;
  1159. //find last modified alternation
  1160. for (var lAlt = getLastValidPosition(); lAlt >= 0; lAlt--) {
  1161. altPos = getMaskSet().validPositions[lAlt];
  1162. if (altPos && altPos.alternation !== undefined) {
  1163. lastAlt = lAlt;
  1164. alternation = getMaskSet().validPositions[lastAlt].alternation;
  1165. if (getTestTemplate(lastAlt).locator[altPos.alternation] !== altPos.locator[altPos.alternation]) {
  1166. break;
  1167. }
  1168. }
  1169. }
  1170. if (alternation !== undefined) {
  1171. //find first decision making position
  1172. lastAlt = parseInt(lastAlt);
  1173. for (var decisionPos in getMaskSet().validPositions) {
  1174. decisionPos = parseInt(decisionPos);
  1175. altPos = getMaskSet().validPositions[decisionPos];
  1176. if (decisionPos >= lastAlt && altPos.alternation !== undefined) {
  1177. var altNdxs = getMaskSet().validPositions[lastAlt].locator[alternation].toString().split(','),
  1178. decisionTaker = altPos.locator[alternation] || altNdxs[0]; //no match in the alternations (length mismatch)
  1179. if (decisionTaker.length > 0) { //no decision taken ~ take first one as decider
  1180. decisionTaker = decisionTaker.split(',')[0];
  1181. }
  1182. for (var mndx = 0; mndx < altNdxs.length; mndx++) {
  1183. if (decisionTaker < altNdxs[mndx]) {
  1184. var possibilityPos, possibilities;
  1185. for (var dp = decisionPos; dp >= 0; dp--) {
  1186. possibilityPos = getMaskSet().validPositions[dp];
  1187. if (possibilityPos !== undefined) {
  1188. possibilities = possibilityPos.locator[alternation]; //store to reset
  1189. //possibilityPos.alternation = undefined;
  1190. possibilityPos.locator[alternation] = parseInt(altNdxs[mndx]);
  1191. break;
  1192. }
  1193. }
  1194. if (decisionTaker !== possibilityPos.locator[alternation]) {
  1195. var validInputs = [],
  1196. staticInputsBeforePos = 0;
  1197. for (i = decisionPos + 1; i < getLastValidPosition() + 1; i++) {
  1198. validPos = getMaskSet().validPositions[i];
  1199. if (validPos) {
  1200. if (validPos.match.fn != null) {
  1201. validInputs.push(validPos.input);
  1202. } else if (i < pos) staticInputsBeforePos++;
  1203. }
  1204. delete getMaskSet().validPositions[i];
  1205. delete getMaskSet().tests[i];
  1206. }
  1207. resetMaskSet(true); //clear getbuffer
  1208. opts.keepStatic = !opts.keepStatic; //disable keepStatic on getMaskLength
  1209. isValidRslt = true;
  1210. while (validInputs.length > 0) {
  1211. var input = validInputs.shift();
  1212. //console.log(input);
  1213. if (input !== opts.skipOptionalPartCharacter) {
  1214. if (!(isValidRslt = isValid(getLastValidPosition() + 1, input, false, true))) {
  1215. break;
  1216. }
  1217. }
  1218. }
  1219. possibilityPos.alternation = alternation;
  1220. possibilityPos.locator[alternation] = possibilities; //reset forceddecision ~ needed for proper delete
  1221. if (isValidRslt) {
  1222. var targetLvp = getLastValidPosition(pos) + 1;
  1223. var staticInputsBeforePosAlternate = 0;
  1224. for (i = decisionPos + 1; i < getLastValidPosition() + 1; i++) {
  1225. validPos = getMaskSet().validPositions[i];
  1226. if (validPos && validPos.match.fn == null && i < pos) {
  1227. staticInputsBeforePosAlternate++;
  1228. }
  1229. }
  1230. pos = pos + (staticInputsBeforePosAlternate - staticInputsBeforePos);
  1231. isValidRslt = isValid(pos > targetLvp ? targetLvp : pos, c, strict, fromSetValid);
  1232. }
  1233. opts.keepStatic = !opts.keepStatic; //enable keepStatic on getMaskLength
  1234. if (!isValidRslt) {
  1235. resetMaskSet();
  1236. getMaskSet().validPositions = $.extend(true, {}, validPsClone);
  1237. } else return isValidRslt;
  1238. }
  1239. }
  1240. }
  1241. break;
  1242. }
  1243. }
  1244. }
  1245. return false;
  1246. }
  1247. //set alternator choice on previous skipped placeholder positions
  1248. function trackbackAlternations(originalPos, newPos) {
  1249. var vp = getMaskSet().validPositions[newPos],
  1250. targetLocator = vp.locator,
  1251. tll = targetLocator.length;
  1252. for (var ps = originalPos; ps < newPos; ps++) {
  1253. if (!isMask(ps)) {
  1254. var tests = getTests(ps),
  1255. bestMatch = tests[0],
  1256. equality = -1;
  1257. $.each(tests, function(ndx, tst) {
  1258. for (var i = 0; i < tll; i++) {
  1259. if (tst.locator[i] && checkAlternationMatch(tst.locator[i].toString().split(","), targetLocator[i].toString().split(",")) && equality < i) {
  1260. equality = i;
  1261. bestMatch = tst;
  1262. }
  1263. }
  1264. });
  1265. setValidPosition(ps, $.extend({}, bestMatch, {
  1266. "input": bestMatch.match.def
  1267. }), true);
  1268. }
  1269. }
  1270. }
  1271. //Check for a nonmask before the pos
  1272. var buffer = getBuffer();
  1273. //find previous valid
  1274. for (var pndx = pos - 1; pndx > -1; pndx--) {
  1275. if (getMaskSet().validPositions[pndx]) {
  1276. break;
  1277. }
  1278. }
  1279. ////fill missing nonmask and valid placeholders
  1280. pndx++;
  1281. for (; pndx < pos; pndx++) {
  1282. //console.log("missing " + pndx + " " + buffer[pndx] + " ismask " + isMask(pndx) + " plchldr " + getPlaceholder(pndx) + " nrt " + getTests(pndx).len);
  1283. 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
  1284. {
  1285. //console.log("inject " + pndx + " " + buffer[pndx]);
  1286. _isValid(pndx, buffer[pndx], true);
  1287. }
  1288. }
  1289. var maskPos = pos,
  1290. result = false,
  1291. positionsClone = $.extend(true, {}, getMaskSet().validPositions); //clone the currentPositions
  1292. //if (fromSetValid && maskPos >= getMaskLength()) {
  1293. // resetMaskSet(true); //masklenght can be altered on the process => reset to get the actual length
  1294. //}
  1295. if (maskPos < getMaskLength()) {
  1296. getBuffer(); //make sure the buffer
  1297. result = _isValid(maskPos, c, strict, fromSetValid);
  1298. if ((!strict || fromSetValid) && result === false) {
  1299. var currentPosValid = getMaskSet().validPositions[maskPos];
  1300. if (currentPosValid && currentPosValid.match.fn === null && (currentPosValid.match.def === c || c === opts.skipOptionalPartCharacter)) {
  1301. result = {
  1302. "caret": seekNext(maskPos)
  1303. };
  1304. } else if ((opts.insertMode || getMaskSet().validPositions[seekNext(maskPos)] === undefined) && !isMask(maskPos)) { //does the input match on a further position?
  1305. for (var nPos = maskPos + 1, snPos = seekNext(maskPos); nPos <= snPos; nPos++) {
  1306. result = _isValid(nPos, c, strict, fromSetValid);
  1307. if (result !== false) {
  1308. trackbackAlternations(maskPos, nPos);
  1309. maskPos = nPos;
  1310. break;
  1311. }
  1312. }
  1313. }
  1314. }
  1315. }
  1316. if (result === false && opts.keepStatic && isComplete(buffer)) { //try fuzzy alternator logic
  1317. result = alternate(pos, c, strict, fromSetValid);
  1318. }
  1319. if (result === true) {
  1320. result = {
  1321. "pos": maskPos
  1322. };
  1323. }
  1324. if ($.isFunction(opts.postValidation) && result !== false && !strict) {
  1325. resetMaskSet(true);
  1326. var postValidResult = opts.postValidation(getBuffer(), opts);
  1327. if (!postValidResult) {
  1328. resetMaskSet(true);
  1329. getMaskSet().validPositions = $.extend(true, {}, positionsClone); //revert validation changes
  1330. result = false;
  1331. } else if (postValidResult.refreshFromBuffer) {
  1332. var refresh = postValidResult.refreshFromBuffer;
  1333. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, postValidResult.buffer);
  1334. resetMaskSet(true);
  1335. result = postValidResult;
  1336. }
  1337. }
  1338. return result;
  1339. }
  1340. function isMask(pos) {
  1341. var test = getTest(pos);
  1342. if (test.fn != null) {
  1343. return test.fn;
  1344. } else if (!opts.keepStatic && getMaskSet().validPositions[pos] === undefined) {
  1345. var tests = getTests(pos),
  1346. staticAlternations = true;
  1347. for (var i = 0; i < tests.length; i++) {
  1348. if (tests[i].match.def !== "" && ( /*tests[i].match.fn !== null || */ (tests[i].alternation === undefined || tests[i].locator[tests[i].alternation].length > 1))) {
  1349. staticAlternations = false;
  1350. break;
  1351. }
  1352. }
  1353. return staticAlternations;
  1354. }
  1355. return false;
  1356. }
  1357. function getMaskLength() {
  1358. var maskLength;
  1359. maxLength = $el.prop("maxLength");
  1360. if (maxLength === -1) maxLength = undefined; /* FF sets no defined max length to -1 */
  1361. var pos, lvp = getLastValidPosition(),
  1362. testPos = getMaskSet().validPositions[lvp],
  1363. ndxIntlzr = testPos !== undefined ? testPos.locator.slice() : undefined;
  1364. for (pos = lvp + 1; testPos === undefined || (testPos.match.fn !== null || (testPos.match.fn === null && testPos.match.def !== "")); pos++) {
  1365. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  1366. ndxIntlzr = testPos.locator.slice();
  1367. }
  1368. var lastTest = getTest(pos - 1);
  1369. maskLength = (lastTest.def !== "") ? pos : pos - 1;
  1370. return (maxLength === undefined || maskLength < maxLength) ? maskLength : maxLength;
  1371. }
  1372. function seekNext(pos, newBlock) {
  1373. var maskL = getMaskLength();
  1374. if (pos >= maskL) return maskL;
  1375. var position = pos;
  1376. while (++position < maskL && ((newBlock === true && (getTest(position).newBlockMarker !== true || !isMask(position))) || (newBlock !== true && !isMask(position) && (opts.nojumps !== true || opts.nojumpsThreshold > position)))) {}
  1377. return position;
  1378. }
  1379. function seekPrevious(pos, newBlock) {
  1380. var position = pos;
  1381. if (position <= 0) return 0;
  1382. while (--position > 0 && ((newBlock === true && getTest(position).newBlockMarker !== true) || (newBlock !== true && !isMask(position)))) {}
  1383. return position;
  1384. }
  1385. function getBufferElement(position) {
  1386. return getMaskSet().validPositions[position] === undefined ? getPlaceholder(position) : getMaskSet().validPositions[position].input;
  1387. }
  1388. function writeBuffer(input, buffer, caretPos, event, triggerInputEvent) {
  1389. if (event && $.isFunction(opts.onBeforeWrite)) {
  1390. var result = opts.onBeforeWrite.call(input, event, buffer, caretPos, opts);
  1391. if (result) {
  1392. if (result.refreshFromBuffer) {
  1393. var refresh = result.refreshFromBuffer;
  1394. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer || buffer);
  1395. resetMaskSet(true);
  1396. buffer = getBuffer();
  1397. }
  1398. caretPos = result.caret !== undefined ? result.caret : caretPos;
  1399. }
  1400. }
  1401. input.inputmask._valueSet(buffer.join(''));
  1402. if (caretPos !== undefined && (event === undefined || event.type !== "blur")) {
  1403. caret(input, caretPos);
  1404. }
  1405. if (triggerInputEvent === true) {
  1406. skipInputEvent = true;
  1407. $(input).trigger("input");
  1408. }
  1409. }
  1410. function getPlaceholder(pos, test) {
  1411. test = test || getTest(pos);
  1412. if (test.placeholder !== undefined) {
  1413. return test.placeholder;
  1414. } else if (test.fn === null) {
  1415. if (!opts.keepStatic && getMaskSet().validPositions[pos] === undefined) {
  1416. var tests = getTests(pos),
  1417. hasAlternations = false,
  1418. prevTest;
  1419. for (var i = 0; i < tests.length; i++) {
  1420. if (prevTest && tests[i].match.def !== "" && (tests[i].match.def !== prevTest.match.def && (tests[i].alternation === undefined || tests[i].alternation === prevTest.alternation))) {
  1421. hasAlternations = true;
  1422. break;
  1423. }
  1424. if (tests[i].match.optionality !== true && tests[i].match.optionalQuantifier !== true) {
  1425. prevTest = tests[i];
  1426. }
  1427. }
  1428. if (hasAlternations) {
  1429. return opts.placeholder.charAt(pos % opts.placeholder.length);
  1430. }
  1431. }
  1432. return test.def;
  1433. } else {
  1434. return opts.placeholder.charAt(pos % opts.placeholder.length);
  1435. }
  1436. }
  1437. function checkVal(input, writeOut, strict, nptvl) {
  1438. var inputValue = nptvl !== undefined ? nptvl.slice() : input.inputmask._valueGet().split(""),
  1439. charCodes = "",
  1440. initialNdx = 0;
  1441. function isTemplateMatch() {
  1442. var isMatch = false;
  1443. var charCodeNdx = getBufferTemplate().slice(initialNdx, seekNext(initialNdx)).join("").indexOf(charCodes);
  1444. if (charCodeNdx !== -1 && !isMask(initialNdx)) {
  1445. isMatch = true;
  1446. var bufferTemplateArr = getBufferTemplate().slice(initialNdx, initialNdx + charCodeNdx);
  1447. for (var i = 0; i < bufferTemplateArr.length; i++) {
  1448. if (bufferTemplateArr[i] !== " ") {
  1449. isMatch = false;
  1450. break;
  1451. }
  1452. }
  1453. }
  1454. return isMatch;
  1455. }
  1456. resetMaskSet();
  1457. getMaskSet().p = seekNext(-1);
  1458. if (writeOut) input.inputmask._valueSet(""); //initial clear
  1459. if (!strict) {
  1460. if (opts.autoUnmask !== true) {
  1461. var staticInput = getBufferTemplate().slice(0, seekNext(-1)).join(''),
  1462. matches = inputValue.join('').match(new RegExp("^" + Inputmask.escapeRegex(staticInput), "g"));
  1463. if (matches && matches.length > 0) {
  1464. inputValue.splice(0, matches.length * staticInput.length);
  1465. initialNdx = seekNext(initialNdx);
  1466. }
  1467. } else {
  1468. initialNdx = seekNext(initialNdx);
  1469. }
  1470. }
  1471. $.each(inputValue, function(ndx, charCode) {
  1472. var keypress = $.Event("keypress");
  1473. keypress.which = charCode.charCodeAt(0);
  1474. charCodes += charCode;
  1475. var lvp = getLastValidPosition(undefined, true),
  1476. lvTest = getMaskSet().validPositions[lvp],
  1477. nextTest = getTestTemplate(lvp + 1, lvTest ? lvTest.locator.slice() : undefined, lvp);
  1478. if (!isTemplateMatch() || strict || opts.autoUnmask) {
  1479. var pos = strict ? ndx : (nextTest.match.fn == null && nextTest.match.optionality && (lvp + 1) < getMaskSet().p ? lvp + 1 : getMaskSet().p);
  1480. keypressEvent.call(input, keypress, true, false, strict, pos);
  1481. initialNdx = pos + 1;
  1482. charCodes = "";
  1483. } else {
  1484. keypressEvent.call(input, keypress, true, false, true, lvp + 1);
  1485. }
  1486. });
  1487. if (writeOut) {
  1488. writeBuffer(input, getBuffer(), $(input).is(":focus") ? seekNext(getLastValidPosition(0)) : undefined, $.Event("checkval"));
  1489. }
  1490. }
  1491. function unmaskedvalue($input) {
  1492. if ($input[0].inputmask && !$input.hasClass("hasDatepicker")) {
  1493. var umValue = [],
  1494. vps = getMaskSet().validPositions;
  1495. for (var pndx in vps) {
  1496. if (vps[pndx].match && vps[pndx].match.fn != null) {
  1497. umValue.push(vps[pndx].input);
  1498. }
  1499. }
  1500. var unmaskedValue = umValue.length === 0 ? null : (isRTL ? umValue.reverse() : umValue).join("");
  1501. if (unmaskedValue !== null) {
  1502. var bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join("");
  1503. if ($.isFunction(opts.onUnMask)) {
  1504. unmaskedValue = (opts.onUnMask.call($input, bufferValue, unmaskedValue, opts) || unmaskedValue);
  1505. }
  1506. }
  1507. return unmaskedValue;
  1508. } else {
  1509. return $input[0].inputmask._valueGet();
  1510. }
  1511. }
  1512. function caret(input, begin, end) {
  1513. function translatePosition(pos) {
  1514. if (isRTL && typeof pos === "number" && (!opts.greedy || opts.placeholder !== "")) {
  1515. 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)
  1516. pos = bffrLght - pos;
  1517. }
  1518. return pos;
  1519. }
  1520. var npt = input.jquery && input.length > 0 ? input[0] : input,
  1521. range;
  1522. if (typeof begin === "number") {
  1523. begin = translatePosition(begin);
  1524. end = translatePosition(end);
  1525. end = (typeof end == "number") ? end : begin;
  1526. if (!$(npt).is(":visible")) {
  1527. return;
  1528. }
  1529. var scrollCalc = $(npt).css("font-size").replace("px", "") * end;
  1530. npt.scrollLeft = scrollCalc > npt.scrollWidth ? scrollCalc : 0;
  1531. if (!androidchrome && opts.insertMode === false && begin === end) end++; //set visualization for insert/overwrite mode
  1532. if (npt.setSelectionRange) {
  1533. npt.selectionStart = begin;
  1534. npt.selectionEnd = end;
  1535. } else if (window.getSelection) {
  1536. range = document.createRange();
  1537. if (npt.firstChild === undefined) {
  1538. var textNode = document.createTextNode("");
  1539. npt.appendChild(textNode);
  1540. }
  1541. range.setStart(npt.firstChild, begin < npt.inputmask._valueGet().length ? begin : npt.inputmask._valueGet().length);
  1542. range.setEnd(npt.firstChild, end < npt.inputmask._valueGet().length ? end : npt.inputmask._valueGet().length);
  1543. range.collapse(true);
  1544. var sel = window.getSelection();
  1545. sel.removeAllRanges();
  1546. sel.addRange(range);
  1547. //npt.focus();
  1548. } else if (npt.createTextRange) {
  1549. range = npt.createTextRange();
  1550. range.collapse(true);
  1551. range.moveEnd("character", end);
  1552. range.moveStart("character", begin);
  1553. range.select();
  1554. }
  1555. } else {
  1556. if (npt.setSelectionRange) {
  1557. begin = npt.selectionStart;
  1558. end = npt.selectionEnd;
  1559. } else if (window.getSelection) {
  1560. range = window.getSelection().getRangeAt(0);
  1561. if (range.commonAncestorContainer.parentNode === npt || range.commonAncestorContainer === npt) {
  1562. begin = range.startOffset;
  1563. end = range.endOffset;
  1564. }
  1565. } else if (document.selection && document.selection.createRange) {
  1566. range = document.selection.createRange();
  1567. begin = 0 - range.duplicate().moveStart("character", -100000);
  1568. end = begin + range.text.length;
  1569. }
  1570. return {
  1571. "begin": translatePosition(begin),
  1572. "end": translatePosition(end)
  1573. };
  1574. }
  1575. }
  1576. function determineLastRequiredPosition(returnDefinition) {
  1577. var buffer = getBuffer(),
  1578. bl = buffer.length,
  1579. pos, lvp = getLastValidPosition(),
  1580. positions = {},
  1581. lvTest = getMaskSet().validPositions[lvp],
  1582. ndxIntlzr = lvTest !== undefined ? lvTest.locator.slice() : undefined,
  1583. testPos;
  1584. for (pos = lvp + 1; pos < buffer.length; pos++) {
  1585. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  1586. ndxIntlzr = testPos.locator.slice();
  1587. positions[pos] = $.extend(true, {}, testPos);
  1588. }
  1589. var lvTestAlt = lvTest && lvTest.alternation !== undefined ? lvTest.locator[lvTest.alternation] : undefined;
  1590. for (pos = bl - 1; pos > lvp; pos--) {
  1591. testPos = positions[pos];
  1592. if ((testPos.match.optionality ||
  1593. testPos.match.optionalQuantifier ||
  1594. (lvTestAlt && ((lvTestAlt !== positions[pos].locator[lvTest.alternation] && testPos.match.fn != null) ||
  1595. (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)) {
  1596. bl--;
  1597. } else break;
  1598. }
  1599. return returnDefinition ? {
  1600. "l": bl,
  1601. "def": positions[bl] ? positions[bl].match : undefined
  1602. } : bl;
  1603. }
  1604. function clearOptionalTail(buffer) {
  1605. var rl = determineLastRequiredPosition(),
  1606. lmib = buffer.length - 1;
  1607. for (; lmib > rl; lmib--) {
  1608. if (isMask(lmib)) break; //fixme ismask is not good enough
  1609. }
  1610. buffer.splice(rl, lmib + 1 - rl);
  1611. return buffer;
  1612. }
  1613. function isComplete(buffer) { //return true / false / undefined (repeat *)
  1614. if ($.isFunction(opts.isComplete)) return opts.isComplete.call($el, buffer, opts);
  1615. if (opts.repeat === "*") return undefined;
  1616. var complete = false,
  1617. lrp = determineLastRequiredPosition(true),
  1618. aml = seekPrevious(lrp.l);
  1619. if (lrp.def === undefined || lrp.def.newBlockMarker || lrp.def.optionality || lrp.def.optionalQuantifier) {
  1620. complete = true;
  1621. for (var i = 0; i <= aml; i++) {
  1622. var test = getTestTemplate(i).match;
  1623. if ((test.fn !== null && getMaskSet().validPositions[i] === undefined && test.optionality !== true && test.optionalQuantifier !== true) || (test.fn === null && buffer[i] !== getPlaceholder(i, test))) {
  1624. complete = false;
  1625. break;
  1626. }
  1627. }
  1628. }
  1629. return complete;
  1630. }
  1631. function isSelection(begin, end) {
  1632. return isRTL ? (begin - end) > 1 || ((begin - end) === 1 && opts.insertMode) :
  1633. (end - begin) > 1 || ((end - begin) === 1 && opts.insertMode);
  1634. }
  1635. function installEventRuler(npt) {
  1636. var events = $._data(npt).events,
  1637. inComposition = false;
  1638. $.each(events, function(eventType, eventHandlers) {
  1639. $.each(eventHandlers, function(ndx, eventHandler) {
  1640. if (eventHandler.namespace === "inputmask") {
  1641. var handler = eventHandler.handler;
  1642. eventHandler.handler = function(e) {
  1643. // console.log("triggered " + e.type);
  1644. if (this.inputmask === undefined) { //happens when cloning an object with jquery.clone
  1645. var imOpts = $(this).data("_inputmask_opts");
  1646. if (imOpts)(new Inputmask(imOpts)).mask(this);
  1647. else $(this).unbind(".inputmask");
  1648. } 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))))) {
  1649. e.preventDefault();
  1650. } else {
  1651. switch (e.type) {
  1652. case "input":
  1653. if (skipInputEvent === true || inComposition === true) {
  1654. skipInputEvent = false;
  1655. return e.preventDefault();
  1656. }
  1657. break;
  1658. case "keydown":
  1659. //Safari 5.1.x - modal dialog fires keypress twice workaround
  1660. skipKeyPressEvent = false;
  1661. inComposition = false;
  1662. break;
  1663. case "keypress":
  1664. if (skipKeyPressEvent === true)
  1665. return e.preventDefault();
  1666. skipKeyPressEvent = true;
  1667. break;
  1668. case "compositionstart":
  1669. inComposition = true;
  1670. break;
  1671. case "compositionupdate":
  1672. skipInputEvent = true;
  1673. break;
  1674. case "compositionend":
  1675. inComposition = false;
  1676. break;
  1677. }
  1678. //console.log("executed " + e.type);
  1679. return handler.apply(this, arguments);
  1680. }
  1681. };
  1682. }
  1683. });
  1684. });
  1685. }
  1686. function patchValueProperty(npt) {
  1687. var valueGet;
  1688. var valueSet;
  1689. function patchValhook(type) {
  1690. if ($.valHooks[type] === undefined || $.valHooks[type].inputmaskpatch !== true) {
  1691. var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function(elem) {
  1692. return elem.value;
  1693. };
  1694. var valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function(elem, value) {
  1695. elem.value = value;
  1696. return elem;
  1697. };
  1698. $.valHooks[type] = {
  1699. get: function(elem) {
  1700. if (elem.inputmask) {
  1701. if (elem.inputmask.opts.autoUnmask) {
  1702. return elem.inputmask.unmaskedvalue();
  1703. } else {
  1704. var result = valhookGet(elem),
  1705. maskset = elem.inputmask.maskset,
  1706. bufferTemplate = maskset._buffer;
  1707. bufferTemplate = bufferTemplate ? bufferTemplate.join("") : "";
  1708. return result !== bufferTemplate ? result : "";
  1709. }
  1710. } else return valhookGet(elem);
  1711. },
  1712. set: function(elem, value) {
  1713. var $elem = $(elem),
  1714. result;
  1715. result = valhookSet(elem, value);
  1716. if (elem.inputmask) {
  1717. $elem.triggerHandler("setvalue.inputmask");
  1718. }
  1719. return result;
  1720. },
  1721. inputmaskpatch: true
  1722. };
  1723. }
  1724. }
  1725. function getter() {
  1726. if (this.inputmask) {
  1727. return this.inputmask.opts.autoUnmask ? this.inputmask.unmaskedvalue() : (valueGet.call(this) !== getBufferTemplate().join("") ? valueGet.call(this) : "");
  1728. } else return valueGet.call(this);
  1729. }
  1730. function setter(value) {
  1731. valueSet.call(this, value);
  1732. if (this.inputmask) {
  1733. $(this).triggerHandler("setvalue.inputmask");
  1734. }
  1735. }
  1736. function installNativeValueSetFallback(npt) {
  1737. $(npt).bind("mouseenter.inputmask", function(event) {
  1738. var $input = $(this),
  1739. input = this,
  1740. value = input.inputmask._valueGet();
  1741. if (value !== "" && value !== getBuffer().join("")) {
  1742. $input.triggerHandler("setvalue.inputmask");
  1743. }
  1744. });
  1745. //!! the bound handlers are executed in the order they where bound
  1746. //reorder the events - the mouseenter event is internally mapped to the mouseover event
  1747. var events = $._data(npt).events;
  1748. var handlers = events.mouseover;
  1749. if (handlers) {
  1750. var ourHandler = handlers[handlers.length - 1];
  1751. for (var i = handlers.length - 1; i > 0; i--) {
  1752. handlers[i] = handlers[i - 1];
  1753. }
  1754. handlers[0] = ourHandler;
  1755. }
  1756. }
  1757. if (!npt.inputmask.__valueGet) {
  1758. if (Object.getOwnPropertyDescriptor && npt.value === undefined) { // && npt.isContentEditable) {
  1759. valueGet = function() {
  1760. return this.textContent;
  1761. };
  1762. valueSet = function(value) {
  1763. this.textContent = value;
  1764. };
  1765. Object.defineProperty(npt, "value", {
  1766. get: getter,
  1767. set: setter
  1768. });
  1769. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  1770. valueGet = npt.__lookupGetter__("value");
  1771. valueSet = npt.__lookupSetter__("value");
  1772. npt.__defineGetter__("value", getter);
  1773. npt.__defineSetter__("value", setter);
  1774. } else { //jquery.val
  1775. valueGet = function() {
  1776. return npt.value;
  1777. };
  1778. valueSet = function(value) {
  1779. npt.value = value;
  1780. };
  1781. patchValhook(npt.type);
  1782. installNativeValueSetFallback(npt);
  1783. }
  1784. npt.inputmask.__valueGet = valueGet; //store native property getter
  1785. npt.inputmask._valueGet = function(overruleRTL) {
  1786. return isRTL && overruleRTL !== true ? valueGet.call(this.el).split("").reverse().join("") : valueGet.call(this.el);
  1787. };
  1788. npt.inputmask.__valueSet = valueSet; //store native property setter
  1789. npt.inputmask._valueSet = function(value) {
  1790. valueSet.call(this.el, isRTL ? value.split("").reverse().join("") : value);
  1791. };
  1792. }
  1793. }
  1794. function handleRemove(input, k, pos, strict) {
  1795. function generalize() {
  1796. if (opts.keepStatic) {
  1797. resetMaskSet(true);
  1798. var validInputs = [],
  1799. lastAlt, positionsClone = $.extend(true, {}, getMaskSet().validPositions);
  1800. //find last alternation
  1801. for (lastAlt = getLastValidPosition(); lastAlt >= 0; lastAlt--) {
  1802. var validPos = getMaskSet().validPositions[lastAlt];
  1803. if (validPos) {
  1804. if (validPos.match.fn != null)
  1805. validInputs.push(validPos.input);
  1806. delete getMaskSet().validPositions[lastAlt];
  1807. if (validPos.alternation !== undefined && validPos.locator[validPos.alternation] === getTestTemplate(lastAlt).locator[validPos.alternation])
  1808. break;
  1809. }
  1810. }
  1811. if (lastAlt > -1)
  1812. while (validInputs.length > 0) {
  1813. getMaskSet().p = seekNext(getLastValidPosition());
  1814. var keypress = $.Event("keypress");
  1815. keypress.which = validInputs.pop().charCodeAt(0);
  1816. keypressEvent.call(input, keypress, true, false, false, getMaskSet().p);
  1817. } else getMaskSet().validPositions = $.extend(true, {}, positionsClone); //restore original positions
  1818. }
  1819. }
  1820. if (opts.numericInput || isRTL) {
  1821. if (k === Inputmask.keyCode.BACKSPACE) {
  1822. k = Inputmask.keyCode.DELETE;
  1823. } else if (k === Inputmask.keyCode.DELETE) {
  1824. k = Inputmask.keyCode.BACKSPACE;
  1825. }
  1826. if (isRTL) {
  1827. var pend = pos.end;
  1828. pos.end = pos.begin;
  1829. pos.begin = pend;
  1830. }
  1831. }
  1832. if (k === Inputmask.keyCode.BACKSPACE && (pos.end - pos.begin < 1 || opts.insertMode === false)) {
  1833. pos.begin = seekPrevious(pos.begin);
  1834. if (getMaskSet().validPositions[pos.begin] !== undefined && (getMaskSet().validPositions[pos.begin].input === opts.groupSeparator || getMaskSet().validPositions[pos.begin].input === opts.radixPoint)) {
  1835. pos.begin--;
  1836. }
  1837. } else if (k === Inputmask.keyCode.DELETE && pos.begin === pos.end) {
  1838. pos.end = isMask(pos.end) ? pos.end + 1 : seekNext(pos.end) + 1;
  1839. if (getMaskSet().validPositions[pos.begin] !== undefined && (getMaskSet().validPositions[pos.begin].input === opts.groupSeparator || getMaskSet().validPositions[pos.begin].input === opts.radixPoint)) {
  1840. pos.end++;
  1841. }
  1842. }
  1843. stripValidPositions(pos.begin, pos.end, false, strict);
  1844. if (strict !== true)
  1845. generalize(); //revert the alternation
  1846. var lvp = getLastValidPosition(pos.begin);
  1847. if (lvp < pos.begin) {
  1848. if (lvp === -1) resetMaskSet();
  1849. getMaskSet().p = seekNext(lvp);
  1850. } else if (strict !== true) {
  1851. getMaskSet().p = pos.begin;
  1852. }
  1853. }
  1854. function keydownEvent(e) {
  1855. var input = this,
  1856. $input = $(input),
  1857. k = e.keyCode,
  1858. pos = caret(input);
  1859. //backspace, delete, and escape get special treatment
  1860. if (k === Inputmask.keyCode.BACKSPACE || k === Inputmask.keyCode.DELETE || (iphone && k === 127) || (e.ctrlKey && k === 88 && !isInputEventSupported("cut"))) { //backspace/delete
  1861. e.preventDefault(); //stop default action but allow propagation
  1862. if (k === 88) undoValue = getBuffer().join("");
  1863. handleRemove(input, k, pos);
  1864. writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join(""));
  1865. if (input.inputmask._valueGet() === getBufferTemplate().join("")) {
  1866. $input.trigger("cleared");
  1867. } else if (isComplete(getBuffer()) === true) {
  1868. $input.trigger("complete");
  1869. }
  1870. if (opts.showTooltip) { //update tooltip
  1871. $input.prop("title", getMaskSet().mask);
  1872. }
  1873. } else if (k === Inputmask.keyCode.END || k === Inputmask.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  1874. setTimeout(function() {
  1875. var caretPos = seekNext(getLastValidPosition());
  1876. if (!opts.insertMode && caretPos === getMaskLength() && !e.shiftKey) caretPos--;
  1877. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
  1878. }, 0);
  1879. } else if ((k === Inputmask.keyCode.HOME && !e.shiftKey) || k === Inputmask.keyCode.PAGE_UP) { //Home or page_up
  1880. caret(input, 0, e.shiftKey ? pos.begin : 0);
  1881. } else if (((opts.undoOnEscape && k === Inputmask.keyCode.ESCAPE) || (k === 90 && e.ctrlKey)) && e.altKey !== true) { //escape && undo && #762
  1882. checkVal(input, true, false, undoValue.split(''));
  1883. $input.click();
  1884. } else if (k === Inputmask.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
  1885. opts.insertMode = !opts.insertMode;
  1886. caret(input, !opts.insertMode && pos.begin === getMaskLength() ? pos.begin - 1 : pos.begin);
  1887. } else if (opts.tabThrough === true && k === Inputmask.keyCode.TAB) {
  1888. if (e.shiftKey === true) {
  1889. if (getTest(pos.begin).fn === null)
  1890. pos.begin = seekNext(pos.begin);
  1891. pos.end = seekPrevious(pos.begin, true);
  1892. pos.begin = seekPrevious(pos.end, true);
  1893. } else {
  1894. pos.begin = seekNext(pos.begin, true);
  1895. pos.end = seekNext(pos.begin, true);
  1896. if (pos.end < getMaskLength()) pos.end--;
  1897. }
  1898. if (pos.begin < getMaskLength()) {
  1899. e.preventDefault();
  1900. caret(input, pos.begin, pos.end);
  1901. }
  1902. } else if (opts.insertMode === false && !e.shiftKey) {
  1903. if (k === Inputmask.keyCode.RIGHT) {
  1904. setTimeout(function() {
  1905. var caretPos = caret(input);
  1906. caret(input, caretPos.begin);
  1907. }, 0);
  1908. } else if (k === Inputmask.keyCode.LEFT) {
  1909. setTimeout(function() {
  1910. var caretPos = caret(input);
  1911. caret(input, isRTL ? caretPos.begin + 1 : caretPos.begin - 1);
  1912. }, 0);
  1913. }
  1914. }
  1915. opts.onKeyDown.call(this, e, getBuffer(), caret(input).begin, opts);
  1916. ignorable = $.inArray(k, opts.ignorables) !== -1;
  1917. }
  1918. function keypressEvent(e, checkval, writeOut, strict, ndx) {
  1919. var input = this,
  1920. $input = $(input),
  1921. k = e.which || e.charCode || e.keyCode;
  1922. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  1923. if (k === Inputmask.keyCode.ENTER && undoValue !== getBuffer().join("")) {
  1924. setTimeout(function() {
  1925. $input.change();
  1926. undoValue = getBuffer().join("");
  1927. }, 0);
  1928. }
  1929. return true;
  1930. } else {
  1931. if (k) {
  1932. //special treat the decimal separator
  1933. if (k === 46 && e.shiftKey === false && opts.radixPoint === ",") k = 44;
  1934. var pos = checkval ? {
  1935. begin: ndx,
  1936. end: ndx
  1937. } : caret(input),
  1938. forwardPosition, c = String.fromCharCode(k);
  1939. //should we clear a possible selection??
  1940. var isSlctn = isSelection(pos.begin, pos.end);
  1941. if (isSlctn) {
  1942. getMaskSet().undoPositions = $.extend(true, {}, getMaskSet().validPositions); //init undobuffer for recovery when not valid
  1943. handleRemove(input, Inputmask.keyCode.DELETE, pos, true);
  1944. pos.begin = getMaskSet().p;
  1945. if (!opts.insertMode) { //preserve some space
  1946. opts.insertMode = !opts.insertMode;
  1947. setValidPosition(pos.begin, strict);
  1948. opts.insertMode = !opts.insertMode;
  1949. }
  1950. isSlctn = !opts.multi;
  1951. }
  1952. getMaskSet().writeOutBuffer = true;
  1953. var p = isRTL && !isSlctn ? pos.end : pos.begin;
  1954. var valResult = isValid(p, c, strict);
  1955. if (valResult !== false) {
  1956. if (valResult !== true) {
  1957. p = valResult.pos !== undefined ? valResult.pos : p; //set new position from isValid
  1958. c = valResult.c !== undefined ? valResult.c : c; //set new char from isValid
  1959. }
  1960. resetMaskSet(true);
  1961. if (valResult.caret !== undefined)
  1962. forwardPosition = valResult.caret;
  1963. else {
  1964. var vps = getMaskSet().validPositions;
  1965. if (!opts.keepStatic && (vps[p + 1] !== undefined && getTests(p + 1, vps[p].locator.slice(), p).length > 1 || vps[p].alternation !== undefined))
  1966. forwardPosition = p + 1;
  1967. else
  1968. forwardPosition = seekNext(p);
  1969. }
  1970. getMaskSet().p = forwardPosition; //needed for checkval
  1971. }
  1972. if (writeOut !== false) {
  1973. var self = this;
  1974. setTimeout(function() {
  1975. opts.onKeyValidation.call(self, valResult, opts);
  1976. }, 0);
  1977. if (getMaskSet().writeOutBuffer && valResult !== false) {
  1978. var buffer = getBuffer();
  1979. writeBuffer(input, buffer, checkval ? undefined : opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition, e, checkval !== true);
  1980. if (checkval !== true) {
  1981. setTimeout(function() { //timeout needed for IE
  1982. if (isComplete(buffer) === true)
  1983. $input.trigger("complete");
  1984. }, 0);
  1985. }
  1986. } else if (isSlctn) {
  1987. getMaskSet().buffer = undefined;
  1988. getMaskSet().validPositions = getMaskSet().undoPositions;
  1989. }
  1990. } else if (isSlctn) {
  1991. getMaskSet().buffer = undefined;
  1992. getMaskSet().validPositions = getMaskSet().undoPositions;
  1993. }
  1994. if (opts.showTooltip) { //update tooltip
  1995. $input.prop("title", getMaskSet().mask);
  1996. }
  1997. if (checkval && $.isFunction(opts.onBeforeWrite)) {
  1998. var result = opts.onBeforeWrite.call(this, e, getBuffer(), forwardPosition, opts);
  1999. if (result && result.refreshFromBuffer) {
  2000. var refresh = result.refreshFromBuffer;
  2001. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer);
  2002. resetMaskSet(true);
  2003. if (result.caret) {
  2004. getMaskSet().p = result.caret;
  2005. }
  2006. }
  2007. }
  2008. e.preventDefault();
  2009. if (checkval) {
  2010. return valResult;
  2011. }
  2012. }
  2013. }
  2014. }
  2015. function pasteEvent(e) {
  2016. var input = this,
  2017. $input = $(input),
  2018. inputValue = input.inputmask._valueGet(true),
  2019. caretPos = caret(input);
  2020. //paste event for IE8 and lower I guess ;-)
  2021. if (e.type === "propertychange" && input.inputmask._valueGet().length <= getMaskLength()) {
  2022. return true;
  2023. } else if (e.type === "paste") {
  2024. var valueBeforeCaret = inputValue.substr(0, caretPos.begin),
  2025. valueAfterCaret = inputValue.substr(caretPos.end, inputValue.length);
  2026. if (valueBeforeCaret === getBufferTemplate().slice(0, caretPos.begin).join("")) valueBeforeCaret = "";
  2027. if (valueAfterCaret === getBufferTemplate().slice(caretPos.end).join("")) valueAfterCaret = "";
  2028. if (window.clipboardData && window.clipboardData.getData) { // IE
  2029. inputValue = valueBeforeCaret + window.clipboardData.getData('Text') + valueAfterCaret;
  2030. } else if (e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData) {
  2031. inputValue = valueBeforeCaret + e.originalEvent.clipboardData.getData('text/plain') + valueAfterCaret;
  2032. }
  2033. }
  2034. var pasteValue = inputValue;
  2035. if ($.isFunction(opts.onBeforePaste)) {
  2036. pasteValue = opts.onBeforePaste.call(input, inputValue, opts);
  2037. if (pasteValue === false) {
  2038. e.preventDefault();
  2039. return false;
  2040. }
  2041. if (!pasteValue)
  2042. pasteValue = inputValue;
  2043. }
  2044. checkVal(input, false, false, isRTL ? pasteValue.split('').reverse() : pasteValue.split(''));
  2045. writeBuffer(input, getBuffer(), undefined, e, true);
  2046. $input.click();
  2047. if (isComplete(getBuffer()) === true)
  2048. $input.trigger("complete");
  2049. return false;
  2050. }
  2051. function inputFallBackEvent(e) { //fallback when keypress & compositionevents fail
  2052. var input = this;
  2053. checkVal(input, true, false);
  2054. if (isComplete(getBuffer()) === true)
  2055. $(input).trigger("complete");
  2056. e.preventDefault();
  2057. }
  2058. function compositionStartEvent(e) {
  2059. var input = this;
  2060. undoValue = getBuffer().join("");
  2061. if (compositionData === "" || e.originalEvent.data.indexOf(compositionData) !== 0) {
  2062. compositionCaretPos = caret(input);
  2063. }
  2064. }
  2065. function compositionUpdateEvent(e) {
  2066. var input = this,
  2067. caretPos = caret(input);
  2068. if (e.originalEvent.data.indexOf(compositionData) === 0) {
  2069. resetMaskSet();
  2070. caretPos = compositionCaretPos;
  2071. }
  2072. var newData = e.originalEvent.data;
  2073. caret(input, caretPos.begin, caretPos.end);
  2074. for (var i = 0; i < newData.length; i++) {
  2075. var keypress = $.Event("keypress");
  2076. keypress.which = newData.charCodeAt(i);
  2077. skipKeyPressEvent = false;
  2078. ignorable = false;
  2079. keypressEvent.call(input, keypress); //needs update
  2080. }
  2081. setTimeout(function() {
  2082. var forwardPosition = getMaskSet().p;
  2083. writeBuffer(input, getBuffer(), opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition);
  2084. }, 0);
  2085. compositionData = e.originalEvent.data;
  2086. }
  2087. function compositionEndEvent(e) {
  2088. //pickup by inputfallback
  2089. }
  2090. function mask(el) {
  2091. $el = $(el);
  2092. //show tooltip
  2093. if (opts.showTooltip)
  2094. $el.prop("title", getMaskSet().mask);
  2095. if (el.dir === "rtl" || opts.rightAlign)
  2096. $el.css("text-align", "right");
  2097. if (el.dir === "rtl" || opts.numericInput) {
  2098. el.dir = "ltr";
  2099. $el.removeAttr("dir");
  2100. el.inputmask.isRTL = true;
  2101. isRTL = true;
  2102. }
  2103. //unbind all events - to make sure that no other mask will interfere when re-masking
  2104. $el.unbind(".inputmask");
  2105. if (($el.is(":input") && isInputTypeSupported($el.attr("type"))) || el.isContentEditable) {
  2106. //bind events
  2107. $el.closest("form").bind("submit", function() { //trigger change on submit if any
  2108. if (undoValue !== getBuffer().join("")) {
  2109. $el.change();
  2110. }
  2111. if (opts.clearMaskOnLostFocus && getLastValidPosition() === -1 && $el[0].inputmask._valueGet && $el[0].inputmask._valueGet() === getBufferTemplate().join("")) {
  2112. $el[0].inputmask._valueSet(""); //clear masktemplete on submit and still has focus
  2113. }
  2114. if (opts.removeMaskOnSubmit) {
  2115. $el.inputmask("remove");
  2116. }
  2117. }).bind("reset", function() {
  2118. setTimeout(function() {
  2119. $el.triggerHandler("setvalue.inputmask");
  2120. }, 0);
  2121. });
  2122. $el.bind("mouseenter.inputmask", function() {
  2123. var $input = $(this),
  2124. input = this;
  2125. mouseEnter = true;
  2126. if (!$input.is(":focus") && opts.showMaskOnHover) {
  2127. if (input.inputmask._valueGet() !== getBuffer().join("")) {
  2128. writeBuffer(input, getBuffer());
  2129. }
  2130. }
  2131. }).bind("blur.inputmask", function(e) {
  2132. var $input = $(this),
  2133. input = this;
  2134. if (input.inputmask) {
  2135. var nptValue = input.inputmask._valueGet(),
  2136. buffer = getBuffer().slice();
  2137. if (undoValue !== buffer.join("")) {
  2138. setTimeout(function() { //change event should be triggered after the other buffer manipulations on blur
  2139. $input.change();
  2140. undoValue = buffer.join("");
  2141. }, 0);
  2142. }
  2143. if (nptValue !== "") {
  2144. if (opts.clearMaskOnLostFocus) {
  2145. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  2146. buffer = [];
  2147. } else { //clearout optional tail of the mask
  2148. clearOptionalTail(buffer);
  2149. }
  2150. }
  2151. if (isComplete(buffer) === false) {
  2152. setTimeout(function() {
  2153. $input.trigger("incomplete");
  2154. }, 0);
  2155. if (opts.clearIncomplete) {
  2156. resetMaskSet();
  2157. if (opts.clearMaskOnLostFocus) {
  2158. buffer = [];
  2159. } else {
  2160. buffer = getBufferTemplate().slice();
  2161. }
  2162. }
  2163. }
  2164. writeBuffer(input, buffer, undefined, e);
  2165. }
  2166. }
  2167. }).bind("focus.inputmask", function(e) {
  2168. var input = this,
  2169. nptValue = input.inputmask._valueGet();
  2170. if (opts.showMaskOnFocus && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue === ""))) {
  2171. if (input.inputmask._valueGet() !== getBuffer().join("")) {
  2172. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
  2173. }
  2174. } else if (mouseEnter === false) { //only executed on focus without mouseenter
  2175. caret(input, seekNext(getLastValidPosition()));
  2176. }
  2177. if (opts.positionCaretOnTab === true) {
  2178. setTimeout(function() {
  2179. caret(input, seekNext(getLastValidPosition()));
  2180. }, 0);
  2181. }
  2182. undoValue = getBuffer().join("");
  2183. }).bind("mouseleave.inputmask", function() {
  2184. var $input = $(this),
  2185. input = this;
  2186. mouseEnter = false;
  2187. if (opts.clearMaskOnLostFocus) {
  2188. var buffer = getBuffer().slice(),
  2189. nptValue = input.inputmask._valueGet();
  2190. if (!$input.is(":focus") && nptValue !== $input.attr("placeholder") && nptValue !== "") {
  2191. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  2192. buffer = [];
  2193. } else { //clearout optional tail of the mask
  2194. clearOptionalTail(buffer);
  2195. }
  2196. writeBuffer(input, buffer);
  2197. }
  2198. }
  2199. }).bind("click.inputmask", function() {
  2200. function doRadixFocus(clickPos) {
  2201. if (opts.radixFocus && opts.radixPoint !== "") {
  2202. var vps = getMaskSet().validPositions;
  2203. if (vps[clickPos] === undefined || (vps[clickPos].input === getPlaceholder(clickPos))) {
  2204. if (clickPos < seekNext(-1)) return true;
  2205. var radixPos = $.inArray(opts.radixPoint, getBuffer());
  2206. if (radixPos !== -1) {
  2207. for (var vp in vps) {
  2208. if (radixPos < vp && vps[vp].input !== getPlaceholder(vp)) {
  2209. return false;
  2210. }
  2211. }
  2212. return true;
  2213. }
  2214. }
  2215. }
  2216. return false;
  2217. }
  2218. var input = this;
  2219. if ($(input).is(":focus")) {
  2220. var selectedCaret = caret(input);
  2221. if (selectedCaret.begin === selectedCaret.end) {
  2222. if (doRadixFocus(selectedCaret.begin)) {
  2223. caret(input, $.inArray(opts.radixPoint, getBuffer()));
  2224. } else {
  2225. var clickPosition = selectedCaret.begin,
  2226. lastPosition = seekNext(getLastValidPosition(clickPosition));
  2227. if (clickPosition < lastPosition) {
  2228. caret(input, !isMask(clickPosition) && !isMask(clickPosition - 1) ? seekNext(clickPosition) : clickPosition);
  2229. } else {
  2230. caret(input, opts.numericInput ? 0 : lastPosition);
  2231. }
  2232. }
  2233. }
  2234. }
  2235. }).bind("dblclick.inputmask", function() {
  2236. var input = this;
  2237. setTimeout(function() {
  2238. caret(input, 0, seekNext(getLastValidPosition()));
  2239. }, 0);
  2240. }).bind(PasteEventType + ".inputmask dragdrop.inputmask drop.inputmask", pasteEvent).bind("cut.inputmask", function(e) {
  2241. skipInputEvent = true; //stop inputFallback
  2242. var input = this,
  2243. $input = $(input),
  2244. pos = caret(input);
  2245. //correct clipboardData
  2246. if (isRTL) {
  2247. var clipboardData = window.clipboardData || e.originalEvent.clipboardData,
  2248. clipData = clipboardData.getData("text").split('').reverse().join('');
  2249. clipboardData.setData("text", clipData);
  2250. }
  2251. handleRemove(input, Inputmask.keyCode.DELETE, pos);
  2252. writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join(""));
  2253. if (input.inputmask._valueGet() === getBufferTemplate().join(''))
  2254. $input.trigger("cleared");
  2255. if (opts.showTooltip) { //update tooltip
  2256. $input.prop("title", getMaskSet().mask);
  2257. }
  2258. }).bind("complete.inputmask", opts.oncomplete).bind("incomplete.inputmask", opts.onincomplete).bind("cleared.inputmask", opts.oncleared);
  2259. $el.bind("keydown.inputmask", keydownEvent).bind("keypress.inputmask", keypressEvent);
  2260. if (!androidfirefox) {
  2261. $el.bind("compositionstart.inputmask", compositionStartEvent).bind("compositionupdate.inputmask", compositionUpdateEvent).bind("compositionend.inputmask", compositionEndEvent);
  2262. }
  2263. if (PasteEventType === "paste") {
  2264. $el.bind("input.inputmask", inputFallBackEvent);
  2265. }
  2266. //if (android || androidfirefox || androidchrome || kindle) {
  2267. // $el.unbind("input.inputmask");
  2268. // $el.bind("input.inputmask", mobileInputEvent);
  2269. //}
  2270. }
  2271. $el.bind("setvalue.inputmask", function() {
  2272. var input = this,
  2273. value = input.inputmask._valueGet();
  2274. input.inputmask._valueSet($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call(input, value, opts) || value) : value);
  2275. checkVal(input, true, false);
  2276. undoValue = getBuffer().join('');
  2277. if ((opts.clearMaskOnLostFocus || opts.clearIncomplete) && input.inputmask._valueGet() === getBufferTemplate().join(''))
  2278. input.inputmask._valueSet('');
  2279. });
  2280. patchValueProperty(el);
  2281. //apply mask
  2282. var initialValue = $.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call(el, el.inputmask._valueGet(), opts) || el.inputmask._valueGet()) : el.inputmask._valueGet();
  2283. checkVal(el, true, false, initialValue.split(''));
  2284. var buffer = getBuffer().slice();
  2285. undoValue = buffer.join('');
  2286. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  2287. var activeElement;
  2288. try {
  2289. activeElement = document.activeElement;
  2290. } catch (e) {}
  2291. if (isComplete(buffer) === false) {
  2292. if (opts.clearIncomplete)
  2293. resetMaskSet();
  2294. }
  2295. if (opts.clearMaskOnLostFocus) {
  2296. if (buffer.join("") === getBufferTemplate().join("")) {
  2297. buffer = [];
  2298. } else {
  2299. clearOptionalTail(buffer);
  2300. }
  2301. }
  2302. writeBuffer(el, buffer);
  2303. if (activeElement === el) { //position the caret when in focus
  2304. caret(el, seekNext(getLastValidPosition()));
  2305. }
  2306. installEventRuler(el);
  2307. }
  2308. //action object
  2309. var valueBuffer;
  2310. if (actionObj !== undefined) {
  2311. switch (actionObj.action) {
  2312. case "isComplete":
  2313. el = actionObj.el;
  2314. $el = $(el);
  2315. maskset = el.inputmask.maskset;
  2316. opts = el.inputmask.opts;
  2317. return isComplete(actionObj.buffer);
  2318. case "unmaskedvalue":
  2319. el = actionObj.el;
  2320. if (el === undefined) {
  2321. //store inputmask instance on the input with element reference
  2322. $el = $({});
  2323. el = $el[0];
  2324. el.inputmask = new Inputmask();
  2325. el.inputmask.opts = opts;
  2326. el.inputmask.el = el;
  2327. el.inputmask.maskset = maskset;
  2328. el.inputmask.isRTL = opts.numericInput;
  2329. if (opts.numericInput) {
  2330. isRTL = true;
  2331. }
  2332. valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call($el, actionObj.value, opts) || actionObj.value) : actionObj.value).split('');
  2333. checkVal($el, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  2334. if ($.isFunction(opts.onBeforeWrite)) opts.onBeforeWrite.call(this, undefined, getBuffer(), 0, opts);
  2335. } else $el = $(el);
  2336. maskset = el.inputmask.maskset;
  2337. opts = el.inputmask.opts;
  2338. isRTL = el.inputmask.isRTL;
  2339. return unmaskedvalue($el);
  2340. case "mask":
  2341. undoValue = getBuffer().join('');
  2342. mask(actionObj.el);
  2343. break;
  2344. case "format":
  2345. $el = $({});
  2346. //store inputmask instance on the input with element reference
  2347. $el[0].inputmask = new Inputmask();
  2348. $el[0].inputmask.opts = opts;
  2349. $el[0].inputmask.el = $el[0];
  2350. $el[0].inputmask.maskset = maskset;
  2351. $el[0].inputmask.isRTL = opts.numericInput;
  2352. if (opts.numericInput) {
  2353. isRTL = true;
  2354. }
  2355. valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call($el, actionObj.value, opts) || actionObj.value) : actionObj.value).split('');
  2356. checkVal($el, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  2357. if ($.isFunction(opts.onBeforeWrite)) opts.onBeforeWrite.call(this, undefined, getBuffer(), 0, opts);
  2358. if (actionObj.metadata) {
  2359. return {
  2360. value: isRTL ? getBuffer().slice().reverse().join('') : getBuffer().join(''),
  2361. metadata: $el.inputmask("getmetadata")
  2362. };
  2363. }
  2364. return isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join("");
  2365. case "isValid":
  2366. $el = $({});
  2367. //store inputmask instance on the input with element reference
  2368. $el[0].inputmask = new Inputmask();
  2369. $el[0].inputmask.opts = opts;
  2370. $el[0].inputmask.el = $el[0];
  2371. $el[0].inputmask.maskset = maskset;
  2372. $el[0].inputmask.isRTL = opts.numericInput;
  2373. if (opts.numericInput) {
  2374. isRTL = true;
  2375. }
  2376. valueBuffer = actionObj.value.split('');
  2377. checkVal($el, false, true, isRTL ? valueBuffer.reverse() : valueBuffer);
  2378. var buffer = getBuffer();
  2379. var rl = determineLastRequiredPosition(),
  2380. lmib = buffer.length - 1;
  2381. for (; lmib > rl; lmib--) {
  2382. if (isMask(lmib)) break;
  2383. }
  2384. buffer.splice(rl, lmib + 1 - rl);
  2385. return isComplete(buffer) && actionObj.value === buffer.join('');
  2386. case "getemptymask":
  2387. el = actionObj.el;
  2388. $el = $(el);
  2389. maskset = el.inputmask.maskset;
  2390. opts = el.inputmask.opts;
  2391. return getBufferTemplate();
  2392. case "remove":
  2393. el = actionObj.el;
  2394. $el = $(el);
  2395. maskset = el.inputmask.maskset;
  2396. opts = el.inputmask.opts;
  2397. //writeout the unmaskedvalue
  2398. el.inputmask._valueSet(unmaskedvalue($el));
  2399. //unbind all events
  2400. $el.unbind(".inputmask");
  2401. //restore the value property
  2402. var valueProperty;
  2403. if (Object.getOwnPropertyDescriptor)
  2404. valueProperty = Object.getOwnPropertyDescriptor(el, "value");
  2405. if (valueProperty && valueProperty.get) {
  2406. if (el.inputmask.__valueGet) {
  2407. Object.defineProperty(el, "value", {
  2408. get: el.inputmask.__valueGet,
  2409. set: el.inputmask.__valueSet
  2410. });
  2411. }
  2412. } else if (document.__lookupGetter__ && el.__lookupGetter__("value")) {
  2413. if (el.inputmask.__valueGet) {
  2414. el.__defineGetter__("value", el.inputmask.__valueGet);
  2415. el.__defineSetter__("value", el.inputmask.__valueSet);
  2416. }
  2417. }
  2418. //clear data
  2419. el.inputmask = undefined;
  2420. break;
  2421. case "getmetadata":
  2422. el = actionObj.el;
  2423. $el = $(el);
  2424. maskset = el.inputmask.maskset;
  2425. opts = el.inputmask.opts;
  2426. if ($.isArray(maskset.metadata)) {
  2427. //find last alternation
  2428. var alternation, lvp = getLastValidPosition();
  2429. for (var firstAlt = lvp; firstAlt >= 0; firstAlt--) {
  2430. if (getMaskSet().validPositions[firstAlt] && getMaskSet().validPositions[firstAlt].alternation !== undefined) {
  2431. alternation = getMaskSet().validPositions[firstAlt].alternation;
  2432. break;
  2433. }
  2434. }
  2435. if (alternation !== undefined)
  2436. return maskset.metadata[getMaskSet().validPositions[lvp].locator[alternation]];
  2437. else return maskset.metadata[0];
  2438. }
  2439. return maskset.metadata;
  2440. }
  2441. }
  2442. }
  2443. //make inputmask available
  2444. window.Inputmask = Inputmask;
  2445. return Inputmask;
  2446. })(jQuery);