inputmask.js 101 KB

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