inputmask.js 102 KB

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