inputmask.js 104 KB

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