inputmask.js 106 KB

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