inputmask.js 104 KB

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