inputmask.js 104 KB

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