inputmask.js 91 KB

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