inputmask.js 94 KB

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