inputmask.js 102 KB

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