inputmask.js 92 KB

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