inputmask.js 91 KB

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