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. supportsInputType: [], //allow extra inputtypes for masking, ex. number can be allowed for numeric alias without pre-/suffix and standard radixpoint, groupSeparator
  72. definitions: {
  73. "9": {
  74. validator: "[0-9]",
  75. cardinality: 1,
  76. definitionSymbol: "*"
  77. },
  78. "a": {
  79. validator: "[A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]",
  80. cardinality: 1,
  81. definitionSymbol: "*"
  82. },
  83. "*": {
  84. validator: "[0-9A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]",
  85. cardinality: 1
  86. }
  87. },
  88. //specify keyCodes which should not be considered in the keypress event, otherwise the preventDefault will stop their default behavior especially in FF
  89. 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],
  90. isComplete: undefined, //override for isComplete - args => buffer, opts - return true || false
  91. canClearPosition: $.noop, //hook to alter the clear behavior in the stripValidPositions args => maskset, position, lastValidPosition, opts => return true|false
  92. postValidation: undefined //hook to postValidate the result from isValid. Usefull for validating the entry as a whole. args => buffer, opts => return true/false
  93. },
  94. masksCache: {},
  95. mask: function(el) {
  96. var input = el.jquery && el.length > 0 ? el[0] : el,
  97. scopedOpts = $.extend(true, {}, this.opts);
  98. importAttributeOptions(el, scopedOpts, $.extend(true, {}, this.userOptions));
  99. var maskset = generateMaskSet(scopedOpts, this.noMasksCache);
  100. if (maskset !== undefined) {
  101. //store inputmask instance on the input with element reference
  102. input.inputmask = input.inputmask || new Inputmask(); //in case of remasking reuse the inputmask object
  103. input.inputmask.opts = scopedOpts;
  104. input.inputmask.noMasksCache = this.noMasksCache;
  105. input.inputmask.el = input;
  106. input.inputmask.maskset = maskset;
  107. input.inputmask.isRTL = false;
  108. $(input).data("_inputmask_opts", scopedOpts);
  109. maskScope({
  110. "action": "mask",
  111. "el": input
  112. }, maskset, input.inputmask.opts);
  113. }
  114. return el;
  115. },
  116. unmaskedvalue: function() {
  117. if (this.el) {
  118. return maskScope({
  119. "action": "unmaskedvalue",
  120. "el": this.el
  121. });
  122. }
  123. },
  124. remove: function() {
  125. if (this.el) {
  126. maskScope({
  127. "action": "remove",
  128. "el": this.el
  129. });
  130. this.el.inputmask = undefined; //delete ~ undefined
  131. return this.el;
  132. }
  133. },
  134. getemptymask: function() { //return the default (empty) mask value, usefull for setting the default value in validation
  135. if (this.el) {
  136. return maskScope({
  137. "action": "getemptymask",
  138. "el": this.el
  139. });
  140. }
  141. },
  142. hasMaskedValue: function() { //check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value
  143. return !this.opts.autoUnmask;
  144. },
  145. isComplete: function() {
  146. if (this.el) {
  147. return maskScope({
  148. "action": "isComplete",
  149. "buffer": this.el.inputmask._valueGet().split(""),
  150. "el": this.el
  151. });
  152. }
  153. },
  154. getmetadata: function() { //return mask metadata if exists
  155. if (this.el) {
  156. return maskScope({
  157. "action": "getmetadata",
  158. "el": this.el
  159. });
  160. }
  161. }
  162. };
  163. //aply defaults, definitions, aliases
  164. Inputmask.extendDefaults = function(options) {
  165. $.extend(Inputmask.prototype.defaults, options);
  166. };
  167. Inputmask.extendDefinitions = function(definition) {
  168. $.extend(Inputmask.prototype.defaults.definitions, definition);
  169. };
  170. Inputmask.extendAliases = function(alias) {
  171. $.extend(Inputmask.prototype.defaults.aliases, alias);
  172. };
  173. //static fn on inputmask
  174. Inputmask.format = function(value, options, metadata) {
  175. var opts = $.extend(true, {}, Inputmask.prototype.defaults, options);
  176. resolveAlias(opts.alias, options, opts);
  177. return maskScope({
  178. "action": "format",
  179. "value": value,
  180. "metadata": metadata //true/false getmetadata
  181. }, generateMaskSet(opts, options && options.definitions !== undefined), opts);
  182. };
  183. Inputmask.unmask = function(value, options) {
  184. var opts = $.extend(true, {}, Inputmask.prototype.defaults, options);
  185. resolveAlias(opts.alias, options, opts);
  186. return maskScope({
  187. "action": "unmaskedvalue",
  188. "value": value
  189. }, generateMaskSet(opts, options && options.definitions !== undefined), opts);
  190. };
  191. Inputmask.isValid = function(value, options) {
  192. var opts = $.extend(true, {}, Inputmask.prototype.defaults, options);
  193. resolveAlias(opts.alias, options, opts);
  194. return maskScope({
  195. "action": "isValid",
  196. "value": value
  197. }, generateMaskSet(opts, options && options.definitions !== undefined), opts);
  198. };
  199. Inputmask.escapeRegex = function(str) {
  200. var specials = ["/", ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\", "$", "^"];
  201. return str.replace(new RegExp("(\\" + specials.join("|\\") + ")", "gim"), "\\$1");
  202. };
  203. Inputmask.keyCode = {
  204. ALT: 18,
  205. BACKSPACE: 8,
  206. CAPS_LOCK: 20,
  207. COMMA: 188,
  208. COMMAND: 91,
  209. COMMAND_LEFT: 91,
  210. COMMAND_RIGHT: 93,
  211. CONTROL: 17,
  212. DELETE: 46,
  213. DOWN: 40,
  214. END: 35,
  215. ENTER: 13,
  216. ESCAPE: 27,
  217. HOME: 36,
  218. INSERT: 45,
  219. LEFT: 37,
  220. MENU: 93,
  221. NUMPAD_ADD: 107,
  222. NUMPAD_DECIMAL: 110,
  223. NUMPAD_DIVIDE: 111,
  224. NUMPAD_ENTER: 108,
  225. NUMPAD_MULTIPLY: 106,
  226. NUMPAD_SUBTRACT: 109,
  227. PAGE_DOWN: 34,
  228. PAGE_UP: 33,
  229. PERIOD: 190,
  230. RIGHT: 39,
  231. SHIFT: 16,
  232. SPACE: 32,
  233. TAB: 9,
  234. UP: 38,
  235. WINDOWS: 91
  236. };
  237. //helper functions
  238. function isInputEventSupported(eventName) {
  239. var el = document.createElement("input"),
  240. evName = "on" + eventName,
  241. isSupported = (evName in el);
  242. if (!isSupported) {
  243. el.setAttribute(evName, "return;");
  244. isSupported = typeof el[evName] == "function";
  245. }
  246. el = null;
  247. return isSupported;
  248. }
  249. function isInputTypeSupported(inputType) {
  250. var isSupported = inputType === "text" || inputType === "tel" || inputType === "password";
  251. if (!isSupported) {
  252. var el = document.createElement("input");
  253. el.setAttribute("type", inputType);
  254. isSupported = el.type === "text"; //apply mask only if the type is not natively supported
  255. el = null;
  256. }
  257. return isSupported;
  258. }
  259. function resolveAlias(aliasStr, options, opts) {
  260. var aliasDefinition = opts.aliases[aliasStr];
  261. if (aliasDefinition) {
  262. if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias, undefined, opts); //alias is another alias
  263. $.extend(true, opts, aliasDefinition); //merge alias definition in the options
  264. $.extend(true, opts, options); //reapply extra given options
  265. return true;
  266. } else //alias not found - try as mask
  267. if (opts.mask === undefined) {
  268. opts.mask = aliasStr;
  269. }
  270. return false;
  271. }
  272. function importAttributeOptions(npt, opts, userOptions) {
  273. var $npt = $(npt),
  274. attrOptions = $npt.data("inputmask");
  275. function importOption(option) {
  276. var optionData = $npt.data("inputmask-" + option.toLowerCase());
  277. if (optionData !== undefined) {
  278. optionData = typeof optionData == "boolean" ? optionData : optionData.toString();
  279. if (option === "mask" && optionData.indexOf("[") === 0) {
  280. userOptions[option] = optionData.replace(/[\s[\]]/g, "").split(",");
  281. userOptions[option][0] = userOptions[option][0].replace("'", "");
  282. userOptions[option][userOptions[option].length - 1] = userOptions[option][userOptions[option].length - 1].replace("'", "");
  283. } else userOptions[option] = optionData;
  284. }
  285. }
  286. if (attrOptions && attrOptions !== "") {
  287. try {
  288. attrOptions = attrOptions.replace(new RegExp("'", "g"), '"');
  289. var dataoptions = $.parseJSON("{" + attrOptions + "}");
  290. $.extend(true, userOptions, dataoptions);
  291. } catch (ex) {
  292. } //need a more relax parseJSON
  293. }
  294. for (var option in opts) {
  295. importOption(option);
  296. }
  297. if (userOptions.alias) {
  298. resolveAlias(userOptions.alias, userOptions, opts);
  299. for (option in opts) {
  300. importOption(option);
  301. }
  302. }
  303. $.extend(true, opts, userOptions);
  304. return opts;
  305. }
  306. function generateMaskSet(opts, nocache) {
  307. var ms;
  308. function analyseMask(mask) {
  309. var tokenizer = /(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?\})\??|[^.?*+^${[]()|\\]+|./g,
  310. escaped = false,
  311. currentToken = new MaskToken(),
  312. match,
  313. m,
  314. openenings = [],
  315. maskTokens = [],
  316. openingToken,
  317. currentOpeningToken,
  318. alternator,
  319. lastMatch,
  320. groupToken;
  321. function MaskToken(isGroup, isOptional, isQuantifier, isAlternator) {
  322. this.matches = [];
  323. this.isGroup = isGroup || false;
  324. this.isOptional = isOptional || false;
  325. this.isQuantifier = isQuantifier || false;
  326. this.isAlternator = isAlternator || false;
  327. this.quantifier = {
  328. min: 1,
  329. max: 1
  330. };
  331. }
  332. //test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, casing: null/upper/lower, def: definitionSymbol, placeholder: placeholder, mask: real maskDefinition}
  333. function insertTestDefinition(mtoken, element, position) {
  334. var maskdef = opts.definitions[element];
  335. position = position !== undefined ? position : mtoken.matches.length;
  336. var prevMatch = mtoken.matches[position - 1];
  337. if (maskdef && !escaped) {
  338. maskdef.placeholder = $.isFunction(maskdef.placeholder) ? maskdef.placeholder.call(this, opts) : maskdef.placeholder;
  339. var prevalidators = maskdef.prevalidator,
  340. prevalidatorsL = prevalidators ? prevalidators.length : 0;
  341. //handle prevalidators
  342. for (var i = 1; i < maskdef.cardinality; i++) {
  343. var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [],
  344. validator = prevalidator.validator,
  345. cardinality = prevalidator.cardinality;
  346. mtoken.matches.splice(position++, 0, {
  347. fn: validator ? typeof validator === "string" ? new RegExp(validator) : new function() {
  348. this.test = validator;
  349. } : new RegExp("."),
  350. cardinality: cardinality ? cardinality : 1,
  351. optionality: mtoken.isOptional,
  352. newBlockMarker: prevMatch === undefined || prevMatch.def !== (maskdef.definitionSymbol || element),
  353. casing: maskdef.casing,
  354. def: maskdef.definitionSymbol || element,
  355. placeholder: maskdef.placeholder,
  356. mask: element
  357. });
  358. prevMatch = mtoken.matches[position - 1];
  359. }
  360. mtoken.matches.splice(position++, 0, {
  361. fn: maskdef.validator ? typeof maskdef.validator == "string" ? new RegExp(maskdef.validator) : new function() {
  362. this.test = maskdef.validator;
  363. } : new RegExp("."),
  364. cardinality: maskdef.cardinality,
  365. optionality: mtoken.isOptional,
  366. newBlockMarker: prevMatch === undefined || prevMatch.def !== (maskdef.definitionSymbol || element),
  367. casing: maskdef.casing,
  368. def: maskdef.definitionSymbol || element,
  369. placeholder: maskdef.placeholder,
  370. mask: element
  371. });
  372. } else {
  373. mtoken.matches.splice(position++, 0, {
  374. fn: null,
  375. cardinality: 0,
  376. optionality: mtoken.isOptional,
  377. newBlockMarker: prevMatch === undefined || prevMatch.def !== element,
  378. casing: null,
  379. def: element,
  380. placeholder: undefined,
  381. mask: element
  382. });
  383. escaped = false;
  384. }
  385. }
  386. function verifyGroupMarker(lastMatch, isOpenGroup) {
  387. if (lastMatch.isGroup) { //this is not a group but a normal mask => convert
  388. lastMatch.isGroup = false;
  389. insertTestDefinition(lastMatch, opts.groupmarker.start, 0);
  390. if (isOpenGroup !== true) {
  391. insertTestDefinition(lastMatch, opts.groupmarker.end);
  392. }
  393. }
  394. }
  395. function maskCurrentToken(m, currentToken, lastMatch, extraCondition) {
  396. if (currentToken.matches.length > 0 && (extraCondition === undefined || extraCondition)) {
  397. lastMatch = currentToken.matches[currentToken.matches.length - 1];
  398. verifyGroupMarker(lastMatch);
  399. }
  400. insertTestDefinition(currentToken, m);
  401. }
  402. function defaultCase() {
  403. if (openenings.length > 0) {
  404. currentOpeningToken = openenings[openenings.length - 1];
  405. maskCurrentToken(m, currentOpeningToken, lastMatch, !currentOpeningToken.isAlternator);
  406. if (currentOpeningToken.isAlternator) { //handle alternator a | b case
  407. alternator = openenings.pop();
  408. for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
  409. alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group
  410. }
  411. if (openenings.length > 0) {
  412. currentOpeningToken = openenings[openenings.length - 1];
  413. currentOpeningToken.matches.push(alternator);
  414. } else {
  415. currentToken.matches.push(alternator);
  416. }
  417. }
  418. } else {
  419. maskCurrentToken(m, currentToken, lastMatch);
  420. }
  421. }
  422. function reverseTokens(maskToken) {
  423. function reverseStatic(st) {
  424. if (st === opts.optionalmarker.start) st = opts.optionalmarker.end;
  425. else if (st === opts.optionalmarker.end) st = opts.optionalmarker.start;
  426. else if (st === opts.groupmarker.start) st = opts.groupmarker.end;
  427. else if (st === opts.groupmarker.end) st = opts.groupmarker.start;
  428. return st;
  429. }
  430. maskToken.matches = maskToken.matches.reverse();
  431. for (var match in maskToken.matches) {
  432. var intMatch = parseInt(match);
  433. if (maskToken.matches[match].isQuantifier && maskToken.matches[intMatch + 1] && maskToken.matches[intMatch + 1].isGroup) { //reposition quantifier
  434. var qt = maskToken.matches[match];
  435. maskToken.matches.splice(match, 1);
  436. maskToken.matches.splice(intMatch + 1, 0, qt);
  437. }
  438. if (maskToken.matches[match].matches !== undefined) {
  439. maskToken.matches[match] = reverseTokens(maskToken.matches[match]);
  440. } else {
  441. maskToken.matches[match] = reverseStatic(maskToken.matches[match]);
  442. }
  443. }
  444. return maskToken;
  445. }
  446. while (match = tokenizer.exec(mask)) {
  447. m = match[0];
  448. if (escaped) {
  449. defaultCase();
  450. continue;
  451. }
  452. switch (m.charAt(0)) {
  453. case opts.escapeChar:
  454. escaped = true;
  455. break;
  456. case opts.optionalmarker.end:
  457. // optional closing
  458. case opts.groupmarker.end:
  459. // Group closing
  460. openingToken = openenings.pop();
  461. if (openingToken !== undefined) {
  462. if (openenings.length > 0) {
  463. currentOpeningToken = openenings[openenings.length - 1];
  464. currentOpeningToken.matches.push(openingToken);
  465. if (currentOpeningToken.isAlternator) { //handle alternator (a) | (b) case
  466. alternator = openenings.pop();
  467. for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
  468. alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group
  469. }
  470. if (openenings.length > 0) {
  471. currentOpeningToken = openenings[openenings.length - 1];
  472. currentOpeningToken.matches.push(alternator);
  473. } else {
  474. currentToken.matches.push(alternator);
  475. }
  476. }
  477. } else {
  478. currentToken.matches.push(openingToken);
  479. }
  480. } else defaultCase();
  481. break;
  482. case opts.optionalmarker.start:
  483. // optional opening
  484. openenings.push(new MaskToken(false, true));
  485. break;
  486. case opts.groupmarker.start:
  487. // Group opening
  488. openenings.push(new MaskToken(true));
  489. break;
  490. case opts.quantifiermarker.start:
  491. //Quantifier
  492. var quantifier = new MaskToken(false, false, true);
  493. m = m.replace(/[{}]/g, "");
  494. var mq = m.split(","),
  495. mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]),
  496. mq1 = mq.length === 1 ? mq0 : (isNaN(mq[1]) ? mq[1] : parseInt(mq[1]));
  497. if (mq1 === "*" || mq1 === "+") {
  498. mq0 = mq1 === "*" ? 0 : 1;
  499. }
  500. quantifier.quantifier = {
  501. min: mq0,
  502. max: mq1
  503. };
  504. if (openenings.length > 0) {
  505. var matches = openenings[openenings.length - 1].matches;
  506. match = matches.pop();
  507. if (!match.isGroup) {
  508. groupToken = new MaskToken(true);
  509. groupToken.matches.push(match);
  510. match = groupToken;
  511. }
  512. matches.push(match);
  513. matches.push(quantifier);
  514. } else {
  515. match = currentToken.matches.pop();
  516. if (!match.isGroup) {
  517. groupToken = new MaskToken(true);
  518. groupToken.matches.push(match);
  519. match = groupToken;
  520. }
  521. currentToken.matches.push(match);
  522. currentToken.matches.push(quantifier);
  523. }
  524. break;
  525. case opts.alternatormarker:
  526. if (openenings.length > 0) {
  527. currentOpeningToken = openenings[openenings.length - 1];
  528. lastMatch = currentOpeningToken.matches.pop();
  529. } else {
  530. lastMatch = currentToken.matches.pop();
  531. }
  532. if (lastMatch.isAlternator) {
  533. openenings.push(lastMatch);
  534. } else {
  535. alternator = new MaskToken(false, false, false, true);
  536. alternator.matches.push(lastMatch);
  537. openenings.push(alternator);
  538. }
  539. break;
  540. default:
  541. defaultCase();
  542. }
  543. }
  544. while (openenings.length > 0) {
  545. openingToken = openenings.pop();
  546. verifyGroupMarker(openingToken, true);
  547. currentToken.matches.push(openingToken);
  548. }
  549. if (currentToken.matches.length > 0) {
  550. lastMatch = currentToken.matches[currentToken.matches.length - 1];
  551. verifyGroupMarker(lastMatch);
  552. maskTokens.push(currentToken);
  553. }
  554. if (opts.numericInput) {
  555. reverseTokens(maskTokens[0]);
  556. }
  557. //console.log(JSON.stringify(maskTokens));
  558. return maskTokens;
  559. }
  560. function generateMask(mask, metadata) {
  561. if (mask === undefined || mask === "") {
  562. return undefined;
  563. } else {
  564. if (mask.length === 1 && opts.greedy === false && opts.repeat !== 0) {
  565. opts.placeholder = "";
  566. } //hide placeholder with single non-greedy mask
  567. if (opts.repeat > 0 || opts.repeat === "*" || opts.repeat === "+") {
  568. var repeatStart = opts.repeat === "*" ? 0 : (opts.repeat === "+" ? 1 : opts.repeat);
  569. mask = opts.groupmarker.start + mask + opts.groupmarker.end + opts.quantifiermarker.start + repeatStart + "," + opts.repeat + opts.quantifiermarker.end;
  570. }
  571. // console.log(mask);
  572. var masksetDefinition;
  573. if (Inputmask.prototype.masksCache[mask] === undefined || nocache === true) {
  574. masksetDefinition = {
  575. "mask": mask,
  576. "maskToken": analyseMask(mask),
  577. "validPositions": {},
  578. "_buffer": undefined,
  579. "buffer": undefined,
  580. "tests": {},
  581. "metadata": metadata
  582. };
  583. if (nocache !== true) {
  584. Inputmask.prototype.masksCache[opts.numericInput ? mask.split("").reverse().join("") : mask] = masksetDefinition;
  585. }
  586. } else masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[mask]);
  587. return masksetDefinition;
  588. }
  589. }
  590. function preProcessMask(mask) {
  591. mask = mask.toString();
  592. // if (opts.numericInput) {
  593. // mask = mask.split('').reverse();
  594. // mask = mask.join('');
  595. // }
  596. return mask;
  597. }
  598. if ($.isFunction(opts.mask)) { //allow mask to be a preprocessing fn - should return a valid mask
  599. opts.mask = opts.mask.call(this, opts);
  600. }
  601. if ($.isArray(opts.mask)) {
  602. if (opts.mask.length > 1) {
  603. opts.keepStatic = opts.keepStatic === undefined ? true : opts.keepStatic; //enable by default when passing multiple masks when the option is not explicitly specified
  604. var altMask = "(";
  605. $.each(opts.numericInput ? opts.mask.reverse() : opts.mask, function(ndx, msk) {
  606. if (altMask.length > 1) {
  607. altMask += ")|(";
  608. }
  609. if (msk.mask !== undefined && !$.isFunction(msk.mask)) {
  610. altMask += preProcessMask(msk.mask);
  611. } else {
  612. altMask += preProcessMask(msk);
  613. }
  614. });
  615. altMask += ")";
  616. return generateMask(altMask, opts.mask);
  617. } else opts.mask = opts.mask.pop();
  618. }
  619. if (opts.mask) {
  620. if (opts.mask.mask !== undefined && !$.isFunction(opts.mask.mask)) {
  621. ms = generateMask(preProcessMask(opts.mask.mask), opts.mask);
  622. } else {
  623. ms = generateMask(preProcessMask(opts.mask), opts.mask);
  624. }
  625. }
  626. return ms;
  627. }
  628. var ua = navigator.userAgent,
  629. iphone = ua.match(new RegExp("iphone", "i")) !== null,
  630. // android = ua.match(new RegExp("android.*safari.*", "i")) !== null,
  631. androidchrome = ua.match(new RegExp("android.*chrome.*", "i")) !== null,
  632. androidfirefox = ua.match(new RegExp("android.*firefox.*", "i")) !== null,
  633. // 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),
  634. PasteEventType = isInputEventSupported("paste") ? "paste" : isInputEventSupported("input") ? "input" : "propertychange";
  635. //if (androidchrome) {
  636. // var browser = navigator.userAgent.match(new RegExp("chrome.*", "i")),
  637. // version = parseInt(new RegExp(/[0-9]+/).exec(browser));
  638. // androidchrome32 = (version == 32);
  639. //}
  640. //masking scope
  641. //actionObj definition see below
  642. function maskScope(actionObj, maskset, opts) {
  643. var isRTL = false,
  644. undoValue,
  645. // compositionValidPos,
  646. compositionCaretPos,
  647. compositionData,
  648. el, $el,
  649. skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
  650. skipInputEvent = false, //skip when triggered from within inputmask
  651. ignorable = false,
  652. maxLength,
  653. mouseEnter = true;
  654. //maskset helperfunctions
  655. function getMaskTemplate(baseOnInput, minimalPos, includeInput) {
  656. minimalPos = minimalPos || 0;
  657. var maskTemplate = [],
  658. ndxIntlzr, pos = 0,
  659. test, testPos;
  660. do {
  661. if (baseOnInput === true && getMaskSet().validPositions[pos]) {
  662. var validPos = getMaskSet().validPositions[pos];
  663. test = validPos.match;
  664. ndxIntlzr = validPos.locator.slice();
  665. maskTemplate.push(includeInput === true ? validPos.input : getPlaceholder(pos, test));
  666. } else {
  667. //console.log("getmasktemplate " + pos + " " + JSON.stringify(ndxIntlzr));
  668. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  669. test = testPos.match;
  670. ndxIntlzr = testPos.locator.slice();
  671. maskTemplate.push(getPlaceholder(pos, test));
  672. }
  673. pos++;
  674. } while ((maxLength === undefined || pos - 1 < maxLength) && test.fn !== null || (test.fn === null && test.def !== "") || minimalPos >= pos);
  675. maskTemplate.pop(); //drop the last one which is empty
  676. return maskTemplate;
  677. }
  678. function getMaskSet() {
  679. return maskset;
  680. }
  681. function resetMaskSet(soft) {
  682. var maskset = getMaskSet();
  683. maskset.buffer = undefined;
  684. maskset.tests = {};
  685. if (soft !== true) {
  686. maskset._buffer = undefined;
  687. maskset.validPositions = {};
  688. maskset.p = 0;
  689. }
  690. }
  691. function getLastValidPosition(closestTo, strict) {
  692. var maskset = getMaskSet(),
  693. lastValidPosition = -1,
  694. valids = maskset.validPositions;
  695. if (closestTo === undefined) closestTo = -1;
  696. var before = lastValidPosition,
  697. after = lastValidPosition;
  698. for (var posNdx in valids) {
  699. var psNdx = parseInt(posNdx);
  700. if (valids[psNdx] && (strict || valids[psNdx].match.fn !== null)) {
  701. if (psNdx <= closestTo) before = psNdx;
  702. if (psNdx >= closestTo) after = psNdx;
  703. }
  704. }
  705. lastValidPosition = (before !== -1 && (closestTo - before) > 1) || after < closestTo ? before : after;
  706. return lastValidPosition;
  707. }
  708. function setValidPosition(pos, validTest, fromSetValid) {
  709. if (opts.insertMode && getMaskSet().validPositions[pos] !== undefined && fromSetValid === undefined) {
  710. //reposition & revalidate others
  711. var positionsClone = $.extend(true, {}, getMaskSet().validPositions),
  712. lvp = getLastValidPosition(),
  713. i;
  714. for (i = pos; i <= lvp; i++) { //clear selection
  715. delete getMaskSet().validPositions[i];
  716. }
  717. getMaskSet().validPositions[pos] = validTest;
  718. var valid = true,
  719. j, vps = getMaskSet().validPositions;
  720. for (i = (j = pos); i <= lvp; i++) {
  721. var t = positionsClone[i];
  722. if (t !== undefined) {
  723. var posMatch = j,
  724. prevPosMatch = -1;
  725. while (posMatch < getMaskLength() && ((t.match.fn == null && vps[i] && (vps[i].match.optionalQuantifier === true || vps[i].match.optionality === true)) || t.match.fn != null)) {
  726. //determine next position
  727. 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))) {
  728. posMatch++;
  729. } else posMatch = seekNext(j);
  730. //does it match
  731. if (positionCanMatchDefinition(posMatch, t.match.def)) {
  732. valid = isValid(posMatch, t.input, true, true) !== false;
  733. j = posMatch;
  734. break;
  735. } else {
  736. valid = t.match.fn == null;
  737. if (prevPosMatch === posMatch) break; //prevent endless loop
  738. prevPosMatch = posMatch;
  739. }
  740. }
  741. }
  742. if (!valid) break;
  743. }
  744. if (!valid) {
  745. getMaskSet().validPositions = $.extend(true, {}, positionsClone);
  746. return false;
  747. }
  748. } else getMaskSet().validPositions[pos] = validTest;
  749. return true;
  750. }
  751. function stripValidPositions(start, end, nocheck, strict) {
  752. var i, startPos = start;
  753. getMaskSet().p = start; //needed for alternated position after overtype selection
  754. for (i = startPos; i < end; i++) { //clear selection
  755. if (getMaskSet().validPositions[i] !== undefined) {
  756. if (nocheck === true || opts.canClearPosition(getMaskSet(), i, getLastValidPosition(), strict, opts) !== false) {
  757. delete getMaskSet().validPositions[i];
  758. }
  759. }
  760. }
  761. resetMaskSet(true);
  762. for (i = startPos + 1; i <= getLastValidPosition();) {
  763. while (getMaskSet().validPositions[startPos] !== undefined) startPos++;
  764. var s = getMaskSet().validPositions[startPos];
  765. if (i < startPos) i = startPos + 1;
  766. // while (getMaskSet().validPositions[i] == undefined) i++;
  767. var t = getMaskSet().validPositions[i];
  768. if (t !== undefined && isMask(i) && s === undefined) {
  769. if (positionCanMatchDefinition(startPos, t.match.def) && isValid(startPos, t.input, true) !== false) {
  770. delete getMaskSet().validPositions[i];
  771. i++;
  772. }
  773. startPos++;
  774. } else i++;
  775. }
  776. //remove radixpoint if needed
  777. var lvp = getLastValidPosition(),
  778. ml = getMaskLength();
  779. if (strict !== true && nocheck !== true && getMaskSet().validPositions[lvp] !== undefined && getMaskSet().validPositions[lvp].input === opts.radixPoint) {
  780. delete getMaskSet().validPositions[lvp];
  781. }
  782. for (i = lvp + 1; i <= ml; i++) {
  783. if (getMaskSet().validPositions[i]) {
  784. delete getMaskSet().validPositions[i];
  785. }
  786. }
  787. resetMaskSet(true);
  788. }
  789. function getTestTemplate(pos, ndxIntlzr, tstPs) {
  790. var testPos = getMaskSet().validPositions[pos];
  791. if (testPos === undefined) {
  792. var testPositions = getTests(pos, ndxIntlzr, tstPs),
  793. lvp = getLastValidPosition(),
  794. lvTest = getMaskSet().validPositions[lvp] || getTests(0)[0],
  795. lvTestAltArr = (lvTest.alternation !== undefined) ? lvTest.locator[lvTest.alternation].toString().split(",") : [];
  796. for (var ndx = 0; ndx < testPositions.length; ndx++) {
  797. testPos = testPositions[ndx];
  798. if (testPos.match &&
  799. (((opts.greedy && testPos.match.optionalQuantifier !== true) || (testPos.match.optionality === false || testPos.match.newBlockMarker === false) && testPos.match.optionalQuantifier !== true) &&
  800. ((lvTest.alternation === undefined || lvTest.alternation !== testPos.alternation) ||
  801. (testPos.locator[lvTest.alternation] !== undefined && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAltArr))))) {
  802. break;
  803. }
  804. }
  805. }
  806. return testPos;
  807. }
  808. function getTest(pos) {
  809. if (getMaskSet().validPositions[pos]) {
  810. return getMaskSet().validPositions[pos].match;
  811. }
  812. return getTests(pos)[0].match;
  813. }
  814. function positionCanMatchDefinition(pos, def) {
  815. var valid = false,
  816. tests = getTests(pos);
  817. for (var tndx = 0; tndx < tests.length; tndx++) {
  818. if (tests[tndx].match && tests[tndx].match.def === def) {
  819. valid = true;
  820. break;
  821. }
  822. }
  823. return valid;
  824. }
  825. function getTests(pos, ndxIntlzr, tstPs, cacheable) {
  826. var maskTokens = getMaskSet().maskToken,
  827. testPos = ndxIntlzr ? tstPs : 0,
  828. ndxInitializer = ndxIntlzr || [0],
  829. matches = [],
  830. insertStop = false,
  831. latestMatch, isFirstMatch;
  832. function resolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) { //ndxInitilizer contains a set of indexes to speedup searches in the mtokens
  833. function handleMatch(match, loopNdx, quantifierRecurse) {
  834. if (testPos > 10000) {
  835. 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);
  836. return true;
  837. }
  838. if (testPos === pos && match.matches === undefined) {
  839. matches.push({
  840. "match": match,
  841. "locator": loopNdx.reverse()
  842. });
  843. return true;
  844. } else if (match.matches !== undefined) {
  845. if (match.isGroup && quantifierRecurse !== match) { //when a group pass along to the quantifier
  846. match = handleMatch(maskToken.matches[$.inArray(match, maskToken.matches) + 1], loopNdx);
  847. if (match) return true;
  848. } else if (match.isOptional) {
  849. var optionalToken = match;
  850. match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  851. if (match) {
  852. latestMatch = matches[matches.length - 1].match;
  853. isFirstMatch = $.inArray(latestMatch, optionalToken.matches) === 0;
  854. if (isFirstMatch) {
  855. insertStop = true; //insert a stop
  856. testPos = pos; //match the position after the group
  857. } else return true;
  858. }
  859. } else if (match.isAlternator) {
  860. var alternateToken = match,
  861. malternateMatches = [],
  862. maltMatches,
  863. currentMatches = matches.slice(),
  864. loopNdxCnt = loopNdx.length;
  865. var altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1;
  866. if (altIndex === -1 || typeof altIndex === "string") {
  867. var currentPos = testPos,
  868. ndxInitializerClone = ndxInitializer.slice(),
  869. altIndexArr = [];
  870. if (typeof altIndex == "string") altIndexArr = altIndex.split(",");
  871. for (var amndx = 0; amndx < alternateToken.matches.length; amndx++) {
  872. matches = [];
  873. match = handleMatch(alternateToken.matches[amndx], [amndx].concat(loopNdx), quantifierRecurse) || match;
  874. if (match !== true && match !== undefined && (altIndexArr[altIndexArr.length - 1] < alternateToken.matches.length)) { //no match in the alternations (length mismatch) => look further
  875. var ntndx = maskToken.matches.indexOf(match) + 1;
  876. if (maskToken.matches.length > ntndx) {
  877. match = handleMatch(maskToken.matches[ntndx], [ntndx].concat(loopNdx.slice(1, loopNdx.length)), quantifierRecurse);
  878. if (match) {
  879. altIndexArr.push(ntndx.toString());
  880. $.each(matches, function(ndx, lmnt) {
  881. lmnt.alternation = loopNdx.length - 1;
  882. });
  883. }
  884. }
  885. }
  886. maltMatches = matches.slice();
  887. testPos = currentPos;
  888. matches = [];
  889. //cloneback
  890. for (var i = 0; i < ndxInitializerClone.length; i++) {
  891. ndxInitializer[i] = ndxInitializerClone[i];
  892. }
  893. //fuzzy merge matches
  894. for (var ndx1 = 0; ndx1 < maltMatches.length; ndx1++) {
  895. var altMatch = maltMatches[ndx1];
  896. altMatch.alternation = altMatch.alternation || loopNdxCnt;
  897. for (var ndx2 = 0; ndx2 < malternateMatches.length; ndx2++) {
  898. var altMatch2 = malternateMatches[ndx2];
  899. //verify equality
  900. if (altMatch.match.mask === altMatch2.match.mask && (typeof altIndex !== "string" || $.inArray(altMatch.locator[altMatch.alternation].toString(), altIndexArr) !== -1)) {
  901. maltMatches.splice(ndx1, 1);
  902. ndx1--;
  903. altMatch2.locator[altMatch.alternation] = altMatch2.locator[altMatch.alternation] + "," + altMatch.locator[altMatch.alternation];
  904. altMatch2.alternation = altMatch.alternation; //we pass the alternation index => used in determineLastRequiredPosition
  905. break;
  906. }
  907. }
  908. }
  909. malternateMatches = malternateMatches.concat(maltMatches);
  910. }
  911. if (typeof altIndex == "string") { //filter matches
  912. malternateMatches = $.map(malternateMatches, function(lmnt, ndx) {
  913. if (isFinite(ndx)) {
  914. var mamatch,
  915. alternation = lmnt.alternation,
  916. altLocArr = lmnt.locator[alternation].toString().split(",");
  917. lmnt.locator[alternation] = undefined;
  918. lmnt.alternation = undefined;
  919. for (var alndx = 0; alndx < altLocArr.length; alndx++) {
  920. mamatch = $.inArray(altLocArr[alndx], altIndexArr) !== -1;
  921. if (mamatch) { //rebuild the locator with valid entries
  922. if (lmnt.locator[alternation] !== undefined) {
  923. lmnt.locator[alternation] += ",";
  924. lmnt.locator[alternation] += altLocArr[alndx];
  925. } else lmnt.locator[alternation] = parseInt(altLocArr[alndx]);
  926. lmnt.alternation = alternation;
  927. }
  928. }
  929. if (lmnt.locator[alternation] !== undefined) return lmnt;
  930. }
  931. });
  932. }
  933. matches = currentMatches.concat(malternateMatches);
  934. testPos = pos;
  935. insertStop = matches.length > 0; //insert a stopelemnt when there is an alternate
  936. } else {
  937. if (alternateToken.matches[altIndex]) { //if not in the initial alternation => look further
  938. match = handleMatch(alternateToken.matches[altIndex], [altIndex].concat(loopNdx), quantifierRecurse);
  939. } else match = false;
  940. }
  941. if (match) return true;
  942. } else if (match.isQuantifier && quantifierRecurse !== maskToken.matches[$.inArray(match, maskToken.matches) - 1]) {
  943. var qt = match;
  944. for (var qndx = (ndxInitializer.length > 0) ? ndxInitializer.shift() : 0;
  945. (qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max)) && testPos <= pos; qndx++) {
  946. var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1];
  947. match = handleMatch(tokenGroup, [qndx].concat(loopNdx), tokenGroup); //set the tokenGroup as quantifierRecurse marker
  948. if (match) {
  949. //get latest match
  950. latestMatch = matches[matches.length - 1].match;
  951. latestMatch.optionalQuantifier = qndx > (qt.quantifier.min - 1);
  952. isFirstMatch = $.inArray(latestMatch, tokenGroup.matches) === 0;
  953. if (isFirstMatch) { //search for next possible match
  954. if (qndx > (qt.quantifier.min - 1)) {
  955. insertStop = true;
  956. testPos = pos; //match the position after the group
  957. break; //stop quantifierloop
  958. } else return true;
  959. } else {
  960. return true;
  961. }
  962. }
  963. }
  964. } else {
  965. match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  966. if (match) return true;
  967. }
  968. } else testPos++;
  969. }
  970. for (var tndx = (ndxInitializer.length > 0 ? ndxInitializer.shift() : 0); tndx < maskToken.matches.length; tndx++) {
  971. if (maskToken.matches[tndx].isQuantifier !== true) {
  972. var match = handleMatch(maskToken.matches[tndx], [tndx].concat(loopNdx), quantifierRecurse);
  973. if (match && testPos === pos) {
  974. return match;
  975. } else if (testPos > pos) {
  976. break;
  977. }
  978. }
  979. }
  980. }
  981. if (cacheable === true && getMaskSet().tests[pos]) {
  982. return getMaskSet().tests[pos];
  983. }
  984. if (ndxIntlzr === undefined) {
  985. var previousPos = pos - 1,
  986. test;
  987. while ((test = getMaskSet().validPositions[previousPos]) === undefined && previousPos > -1) {
  988. if (getMaskSet().tests[previousPos] && (test = getMaskSet().tests[previousPos][0]) !== undefined) {
  989. break;
  990. }
  991. previousPos--;
  992. }
  993. if (test !== undefined && previousPos > -1) {
  994. testPos = previousPos;
  995. ndxInitializer = test.locator.slice();
  996. }
  997. }
  998. for (var mtndx = ndxInitializer.shift(); mtndx < maskTokens.length; mtndx++) {
  999. var match = resolveTestFromToken(maskTokens[mtndx], ndxInitializer, [mtndx]);
  1000. if ((match && testPos === pos) || testPos > pos) {
  1001. break;
  1002. }
  1003. }
  1004. if (matches.length === 0 || insertStop) {
  1005. matches.push({
  1006. "match": {
  1007. fn: null,
  1008. cardinality: 0,
  1009. optionality: true,
  1010. casing: null,
  1011. def: ""
  1012. },
  1013. "locator": []
  1014. });
  1015. }
  1016. getMaskSet().tests[pos] = $.extend(true, [], matches); //set a clone to prevent overwriting some props
  1017. // console.log(pos + " - " + JSON.stringify(matches));
  1018. return getMaskSet().tests[pos];
  1019. }
  1020. function getBufferTemplate() {
  1021. if (getMaskSet()._buffer === undefined) {
  1022. //generate template
  1023. getMaskSet()._buffer = getMaskTemplate(false, 1);
  1024. }
  1025. return getMaskSet()._buffer;
  1026. }
  1027. function getBuffer() {
  1028. if (getMaskSet().buffer === undefined) {
  1029. getMaskSet().buffer = getMaskTemplate(true, getLastValidPosition(), true);
  1030. }
  1031. return getMaskSet().buffer;
  1032. }
  1033. function refreshFromBuffer(start, end, buffer) {
  1034. var i;
  1035. buffer = buffer || getBuffer().slice(); //pass or work on clone
  1036. if (start === true) {
  1037. resetMaskSet();
  1038. start = 0;
  1039. end = buffer.length;
  1040. } else {
  1041. for (i = start; i < end; i++) {
  1042. delete getMaskSet().validPositions[i];
  1043. delete getMaskSet().tests[i];
  1044. }
  1045. }
  1046. for (i = start; i < end; i++) {
  1047. resetMaskSet(true); //prevents clobber from the buffer
  1048. if (buffer[i] !== opts.skipOptionalPartCharacter) {
  1049. isValid(i, buffer[i], true, true);
  1050. }
  1051. }
  1052. }
  1053. function casing(elem, test) {
  1054. switch (test.casing) {
  1055. case "upper":
  1056. elem = elem.toUpperCase();
  1057. break;
  1058. case "lower":
  1059. elem = elem.toLowerCase();
  1060. break;
  1061. }
  1062. return elem;
  1063. }
  1064. function checkAlternationMatch(altArr1, altArr2) {
  1065. var altArrC = opts.greedy ? altArr2 : altArr2.slice(0, 1),
  1066. isMatch = false;
  1067. for (var alndx = 0; alndx < altArr1.length; alndx++) {
  1068. if ($.inArray(altArr1[alndx], altArrC) !== -1) {
  1069. isMatch = true;
  1070. break;
  1071. }
  1072. }
  1073. return isMatch;
  1074. }
  1075. function isValid(pos, c, strict, fromSetValid) { //strict true ~ no correction or autofill
  1076. strict = strict === true; //always set a value to strict to prevent possible strange behavior in the extensions
  1077. function _isValid(position, c, strict, fromSetValid) {
  1078. var rslt = false;
  1079. $.each(getTests(position), function(ndx, tst) {
  1080. var test = tst.match;
  1081. var loopend = c ? 1 : 0,
  1082. chrs = "";
  1083. for (var i = test.cardinality; i > loopend; i--) {
  1084. chrs += getBufferElement(position - (i - 1));
  1085. }
  1086. if (c) {
  1087. chrs += c;
  1088. }
  1089. //return is false or a json object => { pos: ??, c: ??} or true
  1090. rslt = test.fn != null ?
  1091. test.fn.test(chrs, getMaskSet(), position, strict, opts) : (c === test.def || c === opts.skipOptionalPartCharacter) && test.def !== "" ? //non mask
  1092. {
  1093. c: test.def,
  1094. pos: position
  1095. } : false;
  1096. if (rslt !== false) {
  1097. var elem = rslt.c !== undefined ? rslt.c : c;
  1098. elem = (elem === opts.skipOptionalPartCharacter && test.fn === null) ? test.def : elem;
  1099. var validatedPos = position,
  1100. possibleModifiedBuffer = getBuffer();
  1101. if (rslt.remove !== undefined) { //remove position(s)
  1102. if (!$.isArray(rslt.remove)) rslt.remove = [rslt.remove];
  1103. $.each(rslt.remove.sort(function(a, b) {
  1104. return b - a;
  1105. }), function(ndx, lmnt) {
  1106. stripValidPositions(lmnt, lmnt + 1, true);
  1107. });
  1108. }
  1109. if (rslt.insert !== undefined) { //insert position(s)
  1110. if (!$.isArray(rslt.insert)) rslt.insert = [rslt.insert];
  1111. $.each(rslt.insert.sort(function(a, b) {
  1112. return a - b;
  1113. }), function(ndx, lmnt) {
  1114. isValid(lmnt.pos, lmnt.c, true);
  1115. });
  1116. }
  1117. if (rslt.refreshFromBuffer) {
  1118. var refresh = rslt.refreshFromBuffer;
  1119. strict = true;
  1120. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, possibleModifiedBuffer);
  1121. if (rslt.pos === undefined && rslt.c === undefined) {
  1122. rslt.pos = getLastValidPosition();
  1123. return false; //breakout if refreshFromBuffer && nothing to insert
  1124. }
  1125. validatedPos = rslt.pos !== undefined ? rslt.pos : position;
  1126. if (validatedPos !== position) {
  1127. rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
  1128. return false;
  1129. }
  1130. } else if (rslt !== true && rslt.pos !== undefined && rslt.pos !== position) { //their is a position offset
  1131. validatedPos = rslt.pos;
  1132. refreshFromBuffer(position, validatedPos);
  1133. if (validatedPos !== position) {
  1134. rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
  1135. return false;
  1136. }
  1137. }
  1138. if (rslt !== true && rslt.pos === undefined && rslt.c === undefined) {
  1139. return false; //breakout if nothing to insert
  1140. }
  1141. if (ndx > 0) {
  1142. resetMaskSet(true);
  1143. }
  1144. if (!setValidPosition(validatedPos, $.extend({}, tst, {
  1145. "input": casing(elem, test)
  1146. }), fromSetValid)) {
  1147. rslt = false;
  1148. }
  1149. return false; //break from $.each
  1150. }
  1151. });
  1152. return rslt;
  1153. }
  1154. function alternate(pos, c, strict, fromSetValid) {
  1155. var validPsClone = $.extend(true, {}, getMaskSet().validPositions),
  1156. lastAlt,
  1157. alternation,
  1158. isValidRslt,
  1159. altPos, i, validPos;
  1160. //find last modified alternation
  1161. for (var lAlt = getLastValidPosition(); lAlt >= 0; lAlt--) {
  1162. altPos = getMaskSet().validPositions[lAlt];
  1163. if (altPos && altPos.alternation !== undefined) {
  1164. lastAlt = lAlt;
  1165. alternation = getMaskSet().validPositions[lastAlt].alternation;
  1166. if (getTestTemplate(lastAlt).locator[altPos.alternation] !== altPos.locator[altPos.alternation]) {
  1167. break;
  1168. }
  1169. }
  1170. }
  1171. if (alternation !== undefined) {
  1172. //find first decision making position
  1173. lastAlt = parseInt(lastAlt);
  1174. for (var decisionPos in getMaskSet().validPositions) {
  1175. decisionPos = parseInt(decisionPos);
  1176. altPos = getMaskSet().validPositions[decisionPos];
  1177. if (decisionPos >= lastAlt && altPos.alternation !== undefined) {
  1178. var altNdxs = getMaskSet().validPositions[lastAlt].locator[alternation].toString().split(","),
  1179. decisionTaker = altPos.locator[alternation] || altNdxs[0]; //no match in the alternations (length mismatch)
  1180. if (decisionTaker.length > 0) { //no decision taken ~ take first one as decider
  1181. decisionTaker = decisionTaker.split(",")[0];
  1182. }
  1183. for (var mndx = 0; mndx < altNdxs.length; mndx++) {
  1184. if (decisionTaker < altNdxs[mndx]) {
  1185. var possibilityPos, possibilities;
  1186. for (var dp = decisionPos; dp >= 0; dp--) {
  1187. possibilityPos = getMaskSet().validPositions[dp];
  1188. if (possibilityPos !== undefined) {
  1189. possibilities = possibilityPos.locator[alternation]; //store to reset
  1190. //possibilityPos.alternation = undefined;
  1191. possibilityPos.locator[alternation] = parseInt(altNdxs[mndx]);
  1192. break;
  1193. }
  1194. }
  1195. if (decisionTaker !== possibilityPos.locator[alternation]) {
  1196. var validInputs = [],
  1197. staticInputsBeforePos = 0;
  1198. for (i = decisionPos + 1; i < getLastValidPosition() + 1; i++) {
  1199. validPos = getMaskSet().validPositions[i];
  1200. if (validPos) {
  1201. if (validPos.match.fn != null) {
  1202. validInputs.push(validPos.input);
  1203. } else if (i < pos) staticInputsBeforePos++;
  1204. }
  1205. delete getMaskSet().validPositions[i];
  1206. delete getMaskSet().tests[i];
  1207. }
  1208. resetMaskSet(true); //clear getbuffer
  1209. opts.keepStatic = !opts.keepStatic; //disable keepStatic on getMaskLength
  1210. isValidRslt = true;
  1211. while (validInputs.length > 0) {
  1212. var input = validInputs.shift();
  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. }
  1667. skipKeyPressEvent = true;
  1668. break;
  1669. case "compositionstart":
  1670. inComposition = true;
  1671. break;
  1672. case "compositionupdate":
  1673. skipInputEvent = true;
  1674. break;
  1675. case "compositionend":
  1676. inComposition = false;
  1677. break;
  1678. }
  1679. //console.log("executed " + e.type);
  1680. return handler.apply(this, arguments);
  1681. }
  1682. };
  1683. }
  1684. });
  1685. });
  1686. }
  1687. function patchValueProperty(npt) {
  1688. var valueGet;
  1689. var valueSet;
  1690. function patchValhook(type) {
  1691. if ($.valHooks[type] === undefined || $.valHooks[type].inputmaskpatch !== true) {
  1692. var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function(elem) {
  1693. return elem.value;
  1694. };
  1695. var valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function(elem, value) {
  1696. elem.value = value;
  1697. return elem;
  1698. };
  1699. $.valHooks[type] = {
  1700. get: function(elem) {
  1701. if (elem.inputmask) {
  1702. if (elem.inputmask.opts.autoUnmask) {
  1703. return elem.inputmask.unmaskedvalue();
  1704. } else {
  1705. var result = valhookGet(elem),
  1706. maskset = elem.inputmask.maskset,
  1707. bufferTemplate = maskset._buffer;
  1708. bufferTemplate = bufferTemplate ? bufferTemplate.join("") : "";
  1709. return result !== bufferTemplate ? result : "";
  1710. }
  1711. } else return valhookGet(elem);
  1712. },
  1713. set: function(elem, value) {
  1714. var $elem = $(elem),
  1715. result;
  1716. result = valhookSet(elem, value);
  1717. if (elem.inputmask) {
  1718. $elem.triggerHandler("setvalue.inputmask");
  1719. }
  1720. return result;
  1721. },
  1722. inputmaskpatch: true
  1723. };
  1724. }
  1725. }
  1726. function getter() {
  1727. if (this.inputmask) {
  1728. return this.inputmask.opts.autoUnmask ? this.inputmask.unmaskedvalue() : (valueGet.call(this) !== getBufferTemplate().join("") ? valueGet.call(this) : "");
  1729. } else return valueGet.call(this);
  1730. }
  1731. function setter(value) {
  1732. valueSet.call(this, value);
  1733. if (this.inputmask) {
  1734. $(this).triggerHandler("setvalue.inputmask");
  1735. }
  1736. }
  1737. function installNativeValueSetFallback(npt) {
  1738. $(npt).bind("mouseenter.inputmask", function(event) {
  1739. var $input = $(this),
  1740. input = this,
  1741. value = input.inputmask._valueGet();
  1742. if (value !== "" && value !== getBuffer().join("")) {
  1743. $input.triggerHandler("setvalue.inputmask");
  1744. }
  1745. });
  1746. //!! the bound handlers are executed in the order they where bound
  1747. //reorder the events - the mouseenter event is internally mapped to the mouseover event
  1748. var events = $._data(npt).events;
  1749. var handlers = events.mouseover;
  1750. if (handlers) {
  1751. var ourHandler = handlers[handlers.length - 1];
  1752. for (var i = handlers.length - 1; i > 0; i--) {
  1753. handlers[i] = handlers[i - 1];
  1754. }
  1755. handlers[0] = ourHandler;
  1756. }
  1757. }
  1758. if (!npt.inputmask.__valueGet) {
  1759. if (Object.getOwnPropertyDescriptor && npt.value === undefined) { // && npt.isContentEditable) {
  1760. valueGet = function() {
  1761. return this.textContent;
  1762. };
  1763. valueSet = function(value) {
  1764. this.textContent = value;
  1765. };
  1766. Object.defineProperty(npt, "value", {
  1767. get: getter,
  1768. set: setter
  1769. });
  1770. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  1771. valueGet = npt.__lookupGetter__("value");
  1772. valueSet = npt.__lookupSetter__("value");
  1773. npt.__defineGetter__("value", getter);
  1774. npt.__defineSetter__("value", setter);
  1775. } else { //jquery.val
  1776. valueGet = function() {
  1777. return npt.value;
  1778. };
  1779. valueSet = function(value) {
  1780. npt.value = value;
  1781. };
  1782. patchValhook(npt.type);
  1783. installNativeValueSetFallback(npt);
  1784. }
  1785. npt.inputmask.__valueGet = valueGet; //store native property getter
  1786. npt.inputmask._valueGet = function(overruleRTL) {
  1787. return isRTL && overruleRTL !== true ? valueGet.call(this.el).split("").reverse().join("") : valueGet.call(this.el);
  1788. };
  1789. npt.inputmask.__valueSet = valueSet; //store native property setter
  1790. npt.inputmask._valueSet = function(value) {
  1791. valueSet.call(this.el, isRTL ? value.split("").reverse().join("") : value);
  1792. };
  1793. }
  1794. }
  1795. function handleRemove(input, k, pos, strict) {
  1796. function generalize() {
  1797. if (opts.keepStatic) {
  1798. resetMaskSet(true);
  1799. var validInputs = [],
  1800. lastAlt, positionsClone = $.extend(true, {}, getMaskSet().validPositions);
  1801. //find last alternation
  1802. for (lastAlt = getLastValidPosition(); lastAlt >= 0; lastAlt--) {
  1803. var validPos = getMaskSet().validPositions[lastAlt];
  1804. if (validPos) {
  1805. if (validPos.match.fn != null)
  1806. validInputs.push(validPos.input);
  1807. delete getMaskSet().validPositions[lastAlt];
  1808. if (validPos.alternation !== undefined && validPos.locator[validPos.alternation] === getTestTemplate(lastAlt).locator[validPos.alternation])
  1809. break;
  1810. }
  1811. }
  1812. if (lastAlt > -1)
  1813. while (validInputs.length > 0) {
  1814. getMaskSet().p = seekNext(getLastValidPosition());
  1815. var keypress = $.Event("keypress");
  1816. keypress.which = validInputs.pop().charCodeAt(0);
  1817. keypressEvent.call(input, keypress, true, false, false, getMaskSet().p);
  1818. } else getMaskSet().validPositions = $.extend(true, {}, positionsClone); //restore original positions
  1819. }
  1820. }
  1821. if (opts.numericInput || isRTL) {
  1822. if (k === Inputmask.keyCode.BACKSPACE) {
  1823. k = Inputmask.keyCode.DELETE;
  1824. } else if (k === Inputmask.keyCode.DELETE) {
  1825. k = Inputmask.keyCode.BACKSPACE;
  1826. }
  1827. if (isRTL) {
  1828. var pend = pos.end;
  1829. pos.end = pos.begin;
  1830. pos.begin = pend;
  1831. }
  1832. }
  1833. if (k === Inputmask.keyCode.BACKSPACE && (pos.end - pos.begin < 1 || opts.insertMode === false)) {
  1834. pos.begin = seekPrevious(pos.begin);
  1835. if (getMaskSet().validPositions[pos.begin] !== undefined && (getMaskSet().validPositions[pos.begin].input === opts.groupSeparator || getMaskSet().validPositions[pos.begin].input === opts.radixPoint)) {
  1836. pos.begin--;
  1837. }
  1838. } else if (k === Inputmask.keyCode.DELETE && pos.begin === pos.end) {
  1839. pos.end = isMask(pos.end) ? pos.end + 1 : seekNext(pos.end) + 1;
  1840. if (getMaskSet().validPositions[pos.begin] !== undefined && (getMaskSet().validPositions[pos.begin].input === opts.groupSeparator || getMaskSet().validPositions[pos.begin].input === opts.radixPoint)) {
  1841. pos.end++;
  1842. }
  1843. }
  1844. stripValidPositions(pos.begin, pos.end, false, strict);
  1845. if (strict !== true)
  1846. generalize(); //revert the alternation
  1847. var lvp = getLastValidPosition(pos.begin);
  1848. if (lvp < pos.begin) {
  1849. if (lvp === -1) resetMaskSet();
  1850. getMaskSet().p = seekNext(lvp);
  1851. } else if (strict !== true) {
  1852. getMaskSet().p = pos.begin;
  1853. }
  1854. }
  1855. function keydownEvent(e) {
  1856. var input = this,
  1857. $input = $(input),
  1858. k = e.keyCode,
  1859. pos = caret(input);
  1860. //backspace, delete, and escape get special treatment
  1861. if (k === Inputmask.keyCode.BACKSPACE || k === Inputmask.keyCode.DELETE || (iphone && k === 127) || (e.ctrlKey && k === 88 && !isInputEventSupported("cut"))) { //backspace/delete
  1862. e.preventDefault(); //stop default action but allow propagation
  1863. if (k === 88) undoValue = getBuffer().join("");
  1864. handleRemove(input, k, pos);
  1865. writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join(""));
  1866. if (input.inputmask._valueGet() === getBufferTemplate().join("")) {
  1867. $input.trigger("cleared");
  1868. } else if (isComplete(getBuffer()) === true) {
  1869. $input.trigger("complete");
  1870. }
  1871. if (opts.showTooltip) { //update tooltip
  1872. $input.prop("title", getMaskSet().mask);
  1873. }
  1874. } else if (k === Inputmask.keyCode.END || k === Inputmask.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  1875. setTimeout(function() {
  1876. var caretPos = seekNext(getLastValidPosition());
  1877. if (!opts.insertMode && caretPos === getMaskLength() && !e.shiftKey) caretPos--;
  1878. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
  1879. }, 0);
  1880. } else if ((k === Inputmask.keyCode.HOME && !e.shiftKey) || k === Inputmask.keyCode.PAGE_UP) { //Home or page_up
  1881. caret(input, 0, e.shiftKey ? pos.begin : 0);
  1882. } else if (((opts.undoOnEscape && k === Inputmask.keyCode.ESCAPE) || (k === 90 && e.ctrlKey)) && e.altKey !== true) { //escape && undo && #762
  1883. checkVal(input, true, false, undoValue.split(''));
  1884. $input.click();
  1885. } else if (k === Inputmask.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
  1886. opts.insertMode = !opts.insertMode;
  1887. caret(input, !opts.insertMode && pos.begin === getMaskLength() ? pos.begin - 1 : pos.begin);
  1888. } else if (opts.tabThrough === true && k === Inputmask.keyCode.TAB) {
  1889. if (e.shiftKey === true) {
  1890. if (getTest(pos.begin).fn === null)
  1891. pos.begin = seekNext(pos.begin);
  1892. pos.end = seekPrevious(pos.begin, true);
  1893. pos.begin = seekPrevious(pos.end, true);
  1894. } else {
  1895. pos.begin = seekNext(pos.begin, true);
  1896. pos.end = seekNext(pos.begin, true);
  1897. if (pos.end < getMaskLength()) pos.end--;
  1898. }
  1899. if (pos.begin < getMaskLength()) {
  1900. e.preventDefault();
  1901. caret(input, pos.begin, pos.end);
  1902. }
  1903. } else if (opts.insertMode === false && !e.shiftKey) {
  1904. if (k === Inputmask.keyCode.RIGHT) {
  1905. setTimeout(function() {
  1906. var caretPos = caret(input);
  1907. caret(input, caretPos.begin);
  1908. }, 0);
  1909. } else if (k === Inputmask.keyCode.LEFT) {
  1910. setTimeout(function() {
  1911. var caretPos = caret(input);
  1912. caret(input, isRTL ? caretPos.begin + 1 : caretPos.begin - 1);
  1913. }, 0);
  1914. }
  1915. }
  1916. opts.onKeyDown.call(this, e, getBuffer(), caret(input).begin, opts);
  1917. ignorable = $.inArray(k, opts.ignorables) !== -1;
  1918. }
  1919. function keypressEvent(e, checkval, writeOut, strict, ndx) {
  1920. var input = this,
  1921. $input = $(input),
  1922. k = e.which || e.charCode || e.keyCode;
  1923. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  1924. if (k === Inputmask.keyCode.ENTER && undoValue !== getBuffer().join("")) {
  1925. setTimeout(function() {
  1926. $input.change();
  1927. undoValue = getBuffer().join("");
  1928. }, 0);
  1929. }
  1930. return true;
  1931. } else {
  1932. if (k) {
  1933. //special treat the decimal separator
  1934. if (k === 46 && e.shiftKey === false && opts.radixPoint === ",") k = 44;
  1935. var pos = checkval ? {
  1936. begin: ndx,
  1937. end: ndx
  1938. } : caret(input),
  1939. forwardPosition, c = String.fromCharCode(k);
  1940. //should we clear a possible selection??
  1941. var isSlctn = isSelection(pos.begin, pos.end);
  1942. if (isSlctn) {
  1943. getMaskSet().undoPositions = $.extend(true, {}, getMaskSet().validPositions); //init undobuffer for recovery when not valid
  1944. handleRemove(input, Inputmask.keyCode.DELETE, pos, true);
  1945. pos.begin = getMaskSet().p;
  1946. if (!opts.insertMode) { //preserve some space
  1947. opts.insertMode = !opts.insertMode;
  1948. setValidPosition(pos.begin, strict);
  1949. opts.insertMode = !opts.insertMode;
  1950. }
  1951. isSlctn = !opts.multi;
  1952. }
  1953. getMaskSet().writeOutBuffer = true;
  1954. var p = isRTL && !isSlctn ? pos.end : pos.begin;
  1955. var valResult = isValid(p, c, strict);
  1956. if (valResult !== false) {
  1957. if (valResult !== true) {
  1958. p = valResult.pos !== undefined ? valResult.pos : p; //set new position from isValid
  1959. c = valResult.c !== undefined ? valResult.c : c; //set new char from isValid
  1960. }
  1961. resetMaskSet(true);
  1962. if (valResult.caret !== undefined) {
  1963. forwardPosition = valResult.caret;
  1964. } else {
  1965. var vps = getMaskSet().validPositions;
  1966. if (!opts.keepStatic && (vps[p + 1] !== undefined && getTests(p + 1, vps[p].locator.slice(), p).length > 1 || vps[p].alternation !== undefined)) {
  1967. forwardPosition = p + 1;
  1968. } else 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) $input.trigger("complete");
  1983. }, 0);
  1984. }
  1985. } else if (isSlctn) {
  1986. getMaskSet().buffer = undefined;
  1987. getMaskSet().validPositions = getMaskSet().undoPositions;
  1988. }
  1989. } else if (isSlctn) {
  1990. getMaskSet().buffer = undefined;
  1991. getMaskSet().validPositions = getMaskSet().undoPositions;
  1992. }
  1993. if (opts.showTooltip) { //update tooltip
  1994. $input.prop("title", getMaskSet().mask);
  1995. }
  1996. if (checkval && $.isFunction(opts.onBeforeWrite)) {
  1997. var result = opts.onBeforeWrite.call(this, e, getBuffer(), forwardPosition, opts);
  1998. if (result && result.refreshFromBuffer) {
  1999. var refresh = result.refreshFromBuffer;
  2000. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer);
  2001. resetMaskSet(true);
  2002. if (result.caret) {
  2003. getMaskSet().p = result.caret;
  2004. }
  2005. }
  2006. }
  2007. e.preventDefault();
  2008. if (checkval) {
  2009. return valResult;
  2010. }
  2011. }
  2012. }
  2013. }
  2014. function pasteEvent(e) {
  2015. var input = this,
  2016. $input = $(input),
  2017. inputValue = input.inputmask._valueGet(true),
  2018. caretPos = caret(input);
  2019. //paste event for IE8 and lower I guess ;-)
  2020. if (e.type === "propertychange" && input.inputmask._valueGet().length <= getMaskLength()) {
  2021. return true;
  2022. } else if (e.type === "paste") {
  2023. var valueBeforeCaret = inputValue.substr(0, caretPos.begin),
  2024. valueAfterCaret = inputValue.substr(caretPos.end, inputValue.length);
  2025. if (valueBeforeCaret === getBufferTemplate().slice(0, caretPos.begin).join("")) valueBeforeCaret = "";
  2026. if (valueAfterCaret === getBufferTemplate().slice(caretPos.end).join("")) valueAfterCaret = "";
  2027. if (window.clipboardData && window.clipboardData.getData) { // IE
  2028. inputValue = valueBeforeCaret + window.clipboardData.getData("Text") + valueAfterCaret;
  2029. } else if (e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData) {
  2030. inputValue = valueBeforeCaret + e.originalEvent.clipboardData.getData("text/plain") + valueAfterCaret;
  2031. }
  2032. }
  2033. var pasteValue = inputValue;
  2034. if ($.isFunction(opts.onBeforePaste)) {
  2035. pasteValue = opts.onBeforePaste.call(input, inputValue, opts);
  2036. if (pasteValue === false) {
  2037. e.preventDefault();
  2038. return false;
  2039. }
  2040. if (!pasteValue) {
  2041. pasteValue = inputValue;
  2042. }
  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. }
  2050. return false;
  2051. }
  2052. function inputFallBackEvent(e) { //fallback when keypress & compositionevents fail
  2053. var input = this;
  2054. checkVal(input, true, false);
  2055. if (isComplete(getBuffer()) === true)
  2056. $(input).trigger("complete");
  2057. e.preventDefault();
  2058. }
  2059. function compositionStartEvent(e) {
  2060. var input = this;
  2061. undoValue = getBuffer().join("");
  2062. if (compositionData === "" || e.originalEvent.data.indexOf(compositionData) !== 0) {
  2063. compositionCaretPos = caret(input);
  2064. }
  2065. }
  2066. function compositionUpdateEvent(e) {
  2067. var input = this,
  2068. caretPos = caret(input);
  2069. if (e.originalEvent.data.indexOf(compositionData) === 0) {
  2070. resetMaskSet();
  2071. caretPos = compositionCaretPos;
  2072. }
  2073. var newData = e.originalEvent.data;
  2074. caret(input, caretPos.begin, caretPos.end);
  2075. for (var i = 0; i < newData.length; i++) {
  2076. var keypress = $.Event("keypress");
  2077. keypress.which = newData.charCodeAt(i);
  2078. skipKeyPressEvent = false;
  2079. ignorable = false;
  2080. keypressEvent.call(input, keypress); //needs update
  2081. }
  2082. setTimeout(function() {
  2083. var forwardPosition = getMaskSet().p;
  2084. writeBuffer(input, getBuffer(), opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition);
  2085. }, 0);
  2086. compositionData = e.originalEvent.data;
  2087. }
  2088. function compositionEndEvent(e) {
  2089. //pickup by inputfallback
  2090. }
  2091. function mask(el) {
  2092. $el = $(el);
  2093. //show tooltip
  2094. if (opts.showTooltip)
  2095. $el.prop("title", getMaskSet().mask);
  2096. if (el.dir === "rtl" || opts.rightAlign)
  2097. $el.css("text-align", "right");
  2098. if (el.dir === "rtl" || opts.numericInput) {
  2099. el.dir = "ltr";
  2100. $el.removeAttr("dir");
  2101. el.inputmask.isRTL = true;
  2102. isRTL = true;
  2103. }
  2104. //unbind all events - to make sure that no other mask will interfere when re-masking
  2105. $el.unbind(".inputmask");
  2106. if (($el.is(":input") && isInputTypeSupported($el.attr("type"))) || el.isContentEditable) {
  2107. //bind events
  2108. $el.closest("form").bind("submit", function() { //trigger change on submit if any
  2109. if (undoValue !== getBuffer().join("")) {
  2110. $el.change();
  2111. }
  2112. if (opts.clearMaskOnLostFocus && getLastValidPosition() === -1 && $el[0].inputmask._valueGet && $el[0].inputmask._valueGet() === getBufferTemplate().join("")) {
  2113. $el[0].inputmask._valueSet(""); //clear masktemplete on submit and still has focus
  2114. }
  2115. if (opts.removeMaskOnSubmit) {
  2116. $el.inputmask("remove");
  2117. }
  2118. }).bind("reset", function() {
  2119. setTimeout(function() {
  2120. $el.triggerHandler("setvalue.inputmask");
  2121. }, 0);
  2122. });
  2123. $el.bind("mouseenter.inputmask", function() {
  2124. var $input = $(this),
  2125. input = this;
  2126. mouseEnter = true;
  2127. if (!$input.is(":focus") && opts.showMaskOnHover) {
  2128. if (input.inputmask._valueGet() !== getBuffer().join("")) {
  2129. writeBuffer(input, getBuffer());
  2130. }
  2131. }
  2132. }).bind("blur.inputmask", function(e) {
  2133. var $input = $(this),
  2134. input = this;
  2135. if (input.inputmask) {
  2136. var nptValue = input.inputmask._valueGet(),
  2137. buffer = getBuffer().slice();
  2138. if (undoValue !== buffer.join("")) {
  2139. setTimeout(function() { //change event should be triggered after the other buffer manipulations on blur
  2140. $input.change();
  2141. undoValue = buffer.join("");
  2142. }, 0);
  2143. }
  2144. if (nptValue !== "") {
  2145. if (opts.clearMaskOnLostFocus) {
  2146. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  2147. buffer = [];
  2148. } else { //clearout optional tail of the mask
  2149. clearOptionalTail(buffer);
  2150. }
  2151. }
  2152. if (isComplete(buffer) === false) {
  2153. setTimeout(function() {
  2154. $input.trigger("incomplete");
  2155. }, 0);
  2156. if (opts.clearIncomplete) {
  2157. resetMaskSet();
  2158. if (opts.clearMaskOnLostFocus) {
  2159. buffer = [];
  2160. } else {
  2161. buffer = getBufferTemplate().slice();
  2162. }
  2163. }
  2164. }
  2165. writeBuffer(input, buffer, undefined, e);
  2166. }
  2167. }
  2168. }).bind("focus.inputmask", function(e) {
  2169. var input = this,
  2170. nptValue = input.inputmask._valueGet();
  2171. if (opts.showMaskOnFocus && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue === ""))) {
  2172. if (input.inputmask._valueGet() !== getBuffer().join("")) {
  2173. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
  2174. }
  2175. } else if (mouseEnter === false) { //only executed on focus without mouseenter
  2176. caret(input, seekNext(getLastValidPosition()));
  2177. }
  2178. if (opts.positionCaretOnTab === true) {
  2179. setTimeout(function() {
  2180. caret(input, seekNext(getLastValidPosition()));
  2181. }, 0);
  2182. }
  2183. undoValue = getBuffer().join("");
  2184. }).bind("mouseleave.inputmask", function() {
  2185. var $input = $(this),
  2186. input = this;
  2187. mouseEnter = false;
  2188. if (opts.clearMaskOnLostFocus) {
  2189. var buffer = getBuffer().slice(),
  2190. nptValue = input.inputmask._valueGet();
  2191. if (!$input.is(":focus") && nptValue !== $input.attr("placeholder") && nptValue !== "") {
  2192. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  2193. buffer = [];
  2194. } else { //clearout optional tail of the mask
  2195. clearOptionalTail(buffer);
  2196. }
  2197. writeBuffer(input, buffer);
  2198. }
  2199. }
  2200. }).bind("click.inputmask", function() {
  2201. function doRadixFocus(clickPos) {
  2202. if (opts.radixFocus && opts.radixPoint !== "") {
  2203. var vps = getMaskSet().validPositions;
  2204. if (vps[clickPos] === undefined || (vps[clickPos].input === getPlaceholder(clickPos))) {
  2205. if (clickPos < seekNext(-1)) return true;
  2206. var radixPos = $.inArray(opts.radixPoint, getBuffer());
  2207. if (radixPos !== -1) {
  2208. for (var vp in vps) {
  2209. if (radixPos < vp && vps[vp].input !== getPlaceholder(vp)) {
  2210. return false;
  2211. }
  2212. }
  2213. return true;
  2214. }
  2215. }
  2216. }
  2217. return false;
  2218. }
  2219. var input = this;
  2220. if ($(input).is(":focus")) {
  2221. var selectedCaret = caret(input);
  2222. if (selectedCaret.begin === selectedCaret.end) {
  2223. if (doRadixFocus(selectedCaret.begin)) {
  2224. caret(input, $.inArray(opts.radixPoint, getBuffer()));
  2225. } else {
  2226. var clickPosition = selectedCaret.begin,
  2227. lastPosition = seekNext(getLastValidPosition(clickPosition));
  2228. if (clickPosition < lastPosition) {
  2229. caret(input, !isMask(clickPosition) && !isMask(clickPosition - 1) ? seekNext(clickPosition) : clickPosition);
  2230. } else {
  2231. caret(input, opts.numericInput ? 0 : lastPosition);
  2232. }
  2233. }
  2234. }
  2235. }
  2236. }).bind("dblclick.inputmask", function() {
  2237. var input = this;
  2238. setTimeout(function() {
  2239. caret(input, 0, seekNext(getLastValidPosition()));
  2240. }, 0);
  2241. }).bind(PasteEventType + ".inputmask dragdrop.inputmask drop.inputmask", pasteEvent).bind("cut.inputmask", function(e) {
  2242. skipInputEvent = true; //stop inputFallback
  2243. var input = this,
  2244. $input = $(input),
  2245. pos = caret(input);
  2246. //correct clipboardData
  2247. if (isRTL) {
  2248. var clipboardData = window.clipboardData || e.originalEvent.clipboardData,
  2249. clipData = clipboardData.getData("text").split('').reverse().join('');
  2250. clipboardData.setData("text", clipData);
  2251. }
  2252. handleRemove(input, Inputmask.keyCode.DELETE, pos);
  2253. writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join(""));
  2254. if (input.inputmask._valueGet() === getBufferTemplate().join(''))
  2255. $input.trigger("cleared");
  2256. if (opts.showTooltip) { //update tooltip
  2257. $input.prop("title", getMaskSet().mask);
  2258. }
  2259. }).bind("complete.inputmask", opts.oncomplete).bind("incomplete.inputmask", opts.onincomplete).bind("cleared.inputmask", opts.oncleared);
  2260. $el.bind("keydown.inputmask", keydownEvent).bind("keypress.inputmask", keypressEvent);
  2261. if (!androidfirefox) {
  2262. $el.bind("compositionstart.inputmask", compositionStartEvent).bind("compositionupdate.inputmask", compositionUpdateEvent).bind("compositionend.inputmask", compositionEndEvent);
  2263. }
  2264. if (PasteEventType === "paste") {
  2265. $el.bind("input.inputmask", inputFallBackEvent);
  2266. }
  2267. //if (android || androidfirefox || androidchrome || kindle) {
  2268. // $el.unbind("input.inputmask");
  2269. // $el.bind("input.inputmask", mobileInputEvent);
  2270. //}
  2271. }
  2272. $el.bind("setvalue.inputmask", function() {
  2273. var input = this,
  2274. value = input.inputmask._valueGet();
  2275. input.inputmask._valueSet($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call(input, value, opts) || value) : value);
  2276. checkVal(input, true, false);
  2277. undoValue = getBuffer().join('');
  2278. if ((opts.clearMaskOnLostFocus || opts.clearIncomplete) && input.inputmask._valueGet() === getBufferTemplate().join(''))
  2279. input.inputmask._valueSet('');
  2280. });
  2281. patchValueProperty(el);
  2282. //apply mask
  2283. var initialValue = $.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call(el, el.inputmask._valueGet(), opts) || el.inputmask._valueGet()) : el.inputmask._valueGet();
  2284. checkVal(el, true, false, initialValue.split(''));
  2285. var buffer = getBuffer().slice();
  2286. undoValue = buffer.join('');
  2287. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  2288. var activeElement;
  2289. try {
  2290. activeElement = document.activeElement;
  2291. } catch (e) {}
  2292. if (isComplete(buffer) === false) {
  2293. if (opts.clearIncomplete)
  2294. resetMaskSet();
  2295. }
  2296. if (opts.clearMaskOnLostFocus) {
  2297. if (buffer.join("") === getBufferTemplate().join("")) {
  2298. buffer = [];
  2299. } else {
  2300. clearOptionalTail(buffer);
  2301. }
  2302. }
  2303. writeBuffer(el, buffer);
  2304. if (activeElement === el) { //position the caret when in focus
  2305. caret(el, seekNext(getLastValidPosition()));
  2306. }
  2307. installEventRuler(el);
  2308. }
  2309. //action object
  2310. var valueBuffer;
  2311. if (actionObj !== undefined) {
  2312. switch (actionObj.action) {
  2313. case "isComplete":
  2314. el = actionObj.el;
  2315. $el = $(el);
  2316. maskset = el.inputmask.maskset;
  2317. opts = el.inputmask.opts;
  2318. return isComplete(actionObj.buffer);
  2319. case "unmaskedvalue":
  2320. el = actionObj.el;
  2321. if (el === undefined) {
  2322. //store inputmask instance on the input with element reference
  2323. $el = $({});
  2324. el = $el[0];
  2325. el.inputmask = new Inputmask();
  2326. el.inputmask.opts = opts;
  2327. el.inputmask.el = el;
  2328. el.inputmask.maskset = maskset;
  2329. el.inputmask.isRTL = opts.numericInput;
  2330. if (opts.numericInput) {
  2331. isRTL = true;
  2332. }
  2333. valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call($el, actionObj.value, opts) || actionObj.value) : actionObj.value).split('');
  2334. checkVal($el, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  2335. if ($.isFunction(opts.onBeforeWrite)) opts.onBeforeWrite.call(this, undefined, getBuffer(), 0, opts);
  2336. } else $el = $(el);
  2337. maskset = el.inputmask.maskset;
  2338. opts = el.inputmask.opts;
  2339. isRTL = el.inputmask.isRTL;
  2340. return unmaskedvalue($el);
  2341. case "mask":
  2342. undoValue = getBuffer().join('');
  2343. mask(actionObj.el);
  2344. break;
  2345. case "format":
  2346. $el = $({});
  2347. //store inputmask instance on the input with element reference
  2348. $el[0].inputmask = new Inputmask();
  2349. $el[0].inputmask.opts = opts;
  2350. $el[0].inputmask.el = $el[0];
  2351. $el[0].inputmask.maskset = maskset;
  2352. $el[0].inputmask.isRTL = opts.numericInput;
  2353. if (opts.numericInput) {
  2354. isRTL = true;
  2355. }
  2356. valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call($el, actionObj.value, opts) || actionObj.value) : actionObj.value).split('');
  2357. checkVal($el, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  2358. if ($.isFunction(opts.onBeforeWrite)) opts.onBeforeWrite.call(this, undefined, getBuffer(), 0, opts);
  2359. if (actionObj.metadata) {
  2360. return {
  2361. value: isRTL ? getBuffer().slice().reverse().join('') : getBuffer().join(''),
  2362. metadata: $el.inputmask("getmetadata")
  2363. };
  2364. }
  2365. return isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join("");
  2366. case "isValid":
  2367. $el = $({});
  2368. //store inputmask instance on the input with element reference
  2369. $el[0].inputmask = new Inputmask();
  2370. $el[0].inputmask.opts = opts;
  2371. $el[0].inputmask.el = $el[0];
  2372. $el[0].inputmask.maskset = maskset;
  2373. $el[0].inputmask.isRTL = opts.numericInput;
  2374. if (opts.numericInput) {
  2375. isRTL = true;
  2376. }
  2377. valueBuffer = actionObj.value.split('');
  2378. checkVal($el, false, true, isRTL ? valueBuffer.reverse() : valueBuffer);
  2379. var buffer = getBuffer();
  2380. var rl = determineLastRequiredPosition(),
  2381. lmib = buffer.length - 1;
  2382. for (; lmib > rl; lmib--) {
  2383. if (isMask(lmib)) break;
  2384. }
  2385. buffer.splice(rl, lmib + 1 - rl);
  2386. return isComplete(buffer) && actionObj.value === buffer.join('');
  2387. case "getemptymask":
  2388. el = actionObj.el;
  2389. $el = $(el);
  2390. maskset = el.inputmask.maskset;
  2391. opts = el.inputmask.opts;
  2392. return getBufferTemplate();
  2393. case "remove":
  2394. el = actionObj.el;
  2395. $el = $(el);
  2396. maskset = el.inputmask.maskset;
  2397. opts = el.inputmask.opts;
  2398. //writeout the unmaskedvalue
  2399. el.inputmask._valueSet(unmaskedvalue($el));
  2400. //unbind all events
  2401. $el.unbind(".inputmask");
  2402. //restore the value property
  2403. var valueProperty;
  2404. if (Object.getOwnPropertyDescriptor)
  2405. valueProperty = Object.getOwnPropertyDescriptor(el, "value");
  2406. if (valueProperty && valueProperty.get) {
  2407. if (el.inputmask.__valueGet) {
  2408. Object.defineProperty(el, "value", {
  2409. get: el.inputmask.__valueGet,
  2410. set: el.inputmask.__valueSet
  2411. });
  2412. }
  2413. } else if (document.__lookupGetter__ && el.__lookupGetter__("value")) {
  2414. if (el.inputmask.__valueGet) {
  2415. el.__defineGetter__("value", el.inputmask.__valueGet);
  2416. el.__defineSetter__("value", el.inputmask.__valueSet);
  2417. }
  2418. }
  2419. //clear data
  2420. el.inputmask = undefined;
  2421. break;
  2422. case "getmetadata":
  2423. el = actionObj.el;
  2424. $el = $(el);
  2425. maskset = el.inputmask.maskset;
  2426. opts = el.inputmask.opts;
  2427. if ($.isArray(maskset.metadata)) {
  2428. //find last alternation
  2429. var alternation, lvp = getLastValidPosition();
  2430. for (var firstAlt = lvp; firstAlt >= 0; firstAlt--) {
  2431. if (getMaskSet().validPositions[firstAlt] && getMaskSet().validPositions[firstAlt].alternation !== undefined) {
  2432. alternation = getMaskSet().validPositions[firstAlt].alternation;
  2433. break;
  2434. }
  2435. }
  2436. if (alternation !== undefined)
  2437. return maskset.metadata[getMaskSet().validPositions[lvp].locator[alternation]];
  2438. else return maskset.metadata[0];
  2439. }
  2440. return maskset.metadata;
  2441. }
  2442. }
  2443. }
  2444. //make inputmask available
  2445. window.Inputmask = Inputmask;
  2446. return Inputmask;
  2447. })(jQuery);