inputmask.js 105 KB

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