inputmask.js 102 KB

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