inputmask.js 91 KB

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