inputmask.js 104 KB

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