inputmask.js 99 KB

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