inputmask.js 104 KB

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