inputmask.js 112 KB

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