inputmask.js 111 KB

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