inputmask.js 102 KB

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