jquery.inputmask.js 94 KB

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