inputmask.js 103 KB

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