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