inputmask.js 102 KB

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