inputmask.js 111 KB

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