inputmask.js 102 KB

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