inputmask.js 112 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026
  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 || (typeof opts.jitMasking === "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].generatedInput !== true)) {
  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. if (i < startPos) i = startPos + 1;
  764. if (getMaskSet().validPositions[i] !== undefined || !isMask(i)) {
  765. var t = getTestTemplate(i);
  766. if (needsValidation === false && positionsClone[startPos] && positionsClone[startPos].match.def === t.match.def) { //obvious match
  767. getMaskSet().validPositions[startPos] = $.extend(true, {}, positionsClone[startPos]);
  768. getMaskSet().validPositions[startPos].input = t.input;
  769. delete getMaskSet().validPositions[i];
  770. i++;
  771. } else if (positionCanMatchDefinition(startPos, t.match.def)) {
  772. if (isValid(startPos, t.input || getPlaceholder(i), true) !== false) {
  773. delete getMaskSet().validPositions[i];
  774. i++;
  775. needsValidation = true;
  776. }
  777. } else if (!isMask(i)) {
  778. i++;
  779. startPos--;
  780. }
  781. startPos++;
  782. } else i++;
  783. }
  784. resetMaskSet(true);
  785. }
  786. function determineTestTemplate(tests, guessNextBest) {
  787. var testPos,
  788. testPositions = tests,
  789. lvp = getLastValidPosition(),
  790. lvTest = getMaskSet().validPositions[lvp] || getTests(0)[0],
  791. lvTestAltArr = (lvTest.alternation !== undefined) ? lvTest.locator[lvTest.alternation].toString().split(",") : [];
  792. for (var ndx = 0; ndx < testPositions.length; ndx++) {
  793. testPos = testPositions[ndx];
  794. if (testPos.match &&
  795. (((opts.greedy && testPos.match.optionalQuantifier !== true) || (testPos.match.optionality === false || testPos.match.newBlockMarker === false) && testPos.match.optionalQuantifier !== true) &&
  796. ((lvTest.alternation === undefined || lvTest.alternation !== testPos.alternation) ||
  797. (testPos.locator[lvTest.alternation] !== undefined && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAltArr))))) {
  798. if (guessNextBest !== true || (testPos.match.fn === null && !/[0-9a-bA-Z]/.test(testPos.match.def)))
  799. break;
  800. }
  801. }
  802. return testPos;
  803. }
  804. function getTestTemplate(pos, ndxIntlzr, tstPs) {
  805. return getMaskSet().validPositions[pos] || determineTestTemplate(getTests(pos, ndxIntlzr ? ndxIntlzr.slice() : ndxIntlzr, tstPs));
  806. }
  807. function getTest(pos) {
  808. if (getMaskSet().validPositions[pos]) {
  809. return getMaskSet().validPositions[pos];
  810. }
  811. return getTests(pos)[0];
  812. }
  813. function positionCanMatchDefinition(pos, def) {
  814. var valid = false,
  815. tests = getTests(pos);
  816. for (var tndx = 0; tndx < tests.length; tndx++) {
  817. if (tests[tndx].match && tests[tndx].match.def === def) {
  818. valid = true;
  819. break;
  820. }
  821. }
  822. return valid;
  823. }
  824. function getTests(pos, ndxIntlzr, tstPs) {
  825. var maskTokens = getMaskSet().maskToken,
  826. testPos = ndxIntlzr ? tstPs : 0,
  827. ndxInitializer = ndxIntlzr ? ndxIntlzr.slice() : [0],
  828. matches = [],
  829. insertStop = false,
  830. latestMatch,
  831. cacheDependency = ndxIntlzr ? ndxIntlzr.join("") : "";
  832. function resolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) { //ndxInitializer contains a set of indexes to speedup searches in the mtokens
  833. function handleMatch(match, loopNdx, quantifierRecurse) {
  834. function isFirstMatch(latestMatch, tokenGroup) {
  835. var firstMatch = $.inArray(latestMatch, tokenGroup.matches) === 0;
  836. if (!firstMatch) {
  837. $.each(tokenGroup.matches, function (ndx, match) {
  838. if (match.isQuantifier === true) {
  839. firstMatch = isFirstMatch(latestMatch, tokenGroup.matches[ndx - 1]);
  840. if (firstMatch) return false;
  841. }
  842. });
  843. }
  844. return firstMatch;
  845. }
  846. function resolveNdxInitializer(pos, alternateNdx, targetAlternation) {
  847. var bestMatch, indexPos;
  848. if (getMaskSet().tests[pos] || getMaskSet().validPositions[pos]) {
  849. $.each(getMaskSet().tests[pos] || [getMaskSet().validPositions[pos]], function (ndx, lmnt) {
  850. var alternation = targetAlternation !== undefined ? targetAlternation : lmnt.alternation,
  851. ndxPos = lmnt.locator[alternation] !== undefined ? lmnt.locator[alternation].toString().indexOf(alternateNdx) : -1;
  852. if ((indexPos === undefined || ndxPos < indexPos) && ndxPos !== -1) {
  853. bestMatch = lmnt;
  854. indexPos = ndxPos;
  855. }
  856. });
  857. }
  858. return bestMatch ?
  859. bestMatch.locator.slice((targetAlternation !== undefined ? targetAlternation : bestMatch.alternation) + 1) :
  860. targetAlternation !== undefined ? resolveNdxInitializer(pos, alternateNdx) : undefined;
  861. }
  862. function staticCanMatchDefinition(source, target) {
  863. if (source.match.fn === null && target.match.fn !== null) {
  864. return target.match.fn.test(source.match.def, getMaskSet(), pos, false, opts, false);
  865. }
  866. return false;
  867. }
  868. if (testPos > 10000) {
  869. 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;
  870. }
  871. if (testPos === pos && match.matches === undefined) {
  872. matches.push({
  873. "match": match,
  874. "locator": loopNdx.reverse(),
  875. "cd": cacheDependency
  876. });
  877. return true;
  878. } else if (match.matches !== undefined) {
  879. if (match.isGroup && quantifierRecurse !== match) { //when a group pass along to the quantifier
  880. match = handleMatch(maskToken.matches[$.inArray(match, maskToken.matches) + 1], loopNdx);
  881. if (match) return true;
  882. } else if (match.isOptional) {
  883. var optionalToken = match;
  884. match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  885. if (match) {
  886. latestMatch = matches[matches.length - 1].match;
  887. if (isFirstMatch(latestMatch, optionalToken)) {
  888. insertStop = true; //insert a stop
  889. testPos = pos; //match the position after the group
  890. } else return true;
  891. }
  892. } else if (match.isAlternator) {
  893. var alternateToken = match,
  894. malternateMatches = [],
  895. maltMatches,
  896. currentMatches = matches.slice(),
  897. loopNdxCnt = loopNdx.length;
  898. var altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1;
  899. if (altIndex === -1 || typeof altIndex === "string") {
  900. var currentPos = testPos,
  901. ndxInitializerClone = ndxInitializer.slice(),
  902. altIndexArr = [],
  903. amndx;
  904. if (typeof altIndex == "string") {
  905. altIndexArr = altIndex.split(",");
  906. } else {
  907. for (amndx = 0; amndx < alternateToken.matches.length; amndx++) {
  908. altIndexArr.push(amndx);
  909. }
  910. }
  911. for (var ndx = 0; ndx < altIndexArr.length; ndx++) {
  912. amndx = parseInt(altIndexArr[ndx]);
  913. matches = [];
  914. //set the correct ndxInitializer
  915. ndxInitializer = resolveNdxInitializer(testPos, amndx, loopNdxCnt) || ndxInitializerClone.slice();
  916. match = handleMatch(alternateToken.matches[amndx] || maskToken.matches[amndx], [amndx].concat(loopNdx), quantifierRecurse) || match;
  917. if (match !== true && match !== undefined && (altIndexArr[altIndexArr.length - 1] < alternateToken.matches.length)) { //no match in the alternations (length mismatch) => look further
  918. var ntndx = $.inArray(match, maskToken.matches) + 1;
  919. if (maskToken.matches.length > ntndx) {
  920. match = handleMatch(maskToken.matches[ntndx], [ntndx].concat(loopNdx.slice(1, loopNdx.length)), quantifierRecurse);
  921. if (match) {
  922. altIndexArr.push(ntndx.toString());
  923. $.each(matches, function (ndx, lmnt) {
  924. lmnt.alternation = loopNdx.length - 1;
  925. });
  926. }
  927. }
  928. }
  929. maltMatches = matches.slice();
  930. testPos = currentPos;
  931. matches = [];
  932. //fuzzy merge matches
  933. for (var ndx1 = 0; ndx1 < maltMatches.length; ndx1++) {
  934. var altMatch = maltMatches[ndx1], hasMatch = false;
  935. altMatch.alternation = altMatch.alternation || loopNdxCnt;
  936. for (var ndx2 = 0; ndx2 < malternateMatches.length; ndx2++) {
  937. var altMatch2 = malternateMatches[ndx2];
  938. //verify equality
  939. if (typeof altIndex !== "string" || $.inArray(altMatch.locator[altMatch.alternation].toString(), altIndexArr) !== -1) {
  940. if (altMatch.match.def === altMatch2.match.def || staticCanMatchDefinition(altMatch, altMatch2)) {
  941. hasMatch = altMatch.match.nativeDef === altMatch2.match.nativeDef;
  942. // if (altMatch.alternation != altMatch2.alternation) {
  943. // console.log("alternation mismatch");
  944. // }
  945. if (altMatch.alternation == altMatch2.alternation && //can we merge if the alternation is different?? TODO TOCHECK INVESTIGATE
  946. altMatch2.locator[altMatch2.alternation].toString().indexOf(altMatch.locator[altMatch.alternation]) === -1) {
  947. altMatch2.locator[altMatch2.alternation] = altMatch2.locator[altMatch2.alternation] + "," + altMatch.locator[altMatch.alternation];
  948. altMatch2.alternation = altMatch.alternation; //we pass the alternation index => used in determineLastRequiredPosition
  949. if (altMatch.match.fn == null) { //staticCanMatchDefinition => set no alternate on match
  950. altMatch2.na = altMatch2.na || altMatch.locator[altMatch.alternation].toString();
  951. if (altMatch2.na.indexOf(altMatch.locator[altMatch.alternation]) === -1)
  952. altMatch2.na = altMatch2.na + "," + altMatch.locator[altMatch.alternation];
  953. }
  954. }
  955. break;
  956. }
  957. }
  958. }
  959. if (!hasMatch) {
  960. malternateMatches.push(altMatch);
  961. }
  962. }
  963. }
  964. if (typeof altIndex == "string") { //filter matches
  965. malternateMatches = $.map(malternateMatches, function (lmnt, ndx) {
  966. if (isFinite(ndx)) {
  967. var mamatch,
  968. alternation = lmnt.alternation,
  969. altLocArr = lmnt.locator[alternation].toString().split(",");
  970. lmnt.locator[alternation] = undefined;
  971. lmnt.alternation = undefined;
  972. for (var alndx = 0; alndx < altLocArr.length; alndx++) {
  973. mamatch = $.inArray(altLocArr[alndx], altIndexArr) !== -1;
  974. if (mamatch) { //rebuild the locator with valid entries
  975. if (lmnt.locator[alternation] !== undefined) {
  976. lmnt.locator[alternation] += ",";
  977. lmnt.locator[alternation] += altLocArr[alndx];
  978. } else lmnt.locator[alternation] = parseInt(altLocArr[alndx]);
  979. lmnt.alternation = alternation;
  980. }
  981. }
  982. if (lmnt.locator[alternation] !== undefined) return lmnt;
  983. }
  984. });
  985. }
  986. matches = currentMatches.concat(malternateMatches);
  987. testPos = pos;
  988. insertStop = matches.length > 0; //insert a stopelemnt when there is an alternate - needed for non-greedy option
  989. //cloneback
  990. ndxInitializer = ndxInitializerClone.slice();
  991. } else {
  992. // if (alternateToken.matches[altIndex]) { //if not in the initial alternation => look further
  993. match = handleMatch(alternateToken.matches[altIndex] || maskToken.matches[altIndex], [altIndex].concat(loopNdx), quantifierRecurse);
  994. // } else match = false;
  995. }
  996. if (match) return true;
  997. } else if (match.isQuantifier && quantifierRecurse !== maskToken.matches[$.inArray(match, maskToken.matches) - 1]) {
  998. var qt = match;
  999. for (var qndx = (ndxInitializer.length > 0) ? ndxInitializer.shift() : 0; (qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max)) && testPos <= pos; qndx++) {
  1000. var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1];
  1001. match = handleMatch(tokenGroup, [qndx].concat(loopNdx), tokenGroup); //set the tokenGroup as quantifierRecurse marker
  1002. if (match) {
  1003. //get latest match
  1004. latestMatch = matches[matches.length - 1].match;
  1005. latestMatch.optionalQuantifier = qndx > (qt.quantifier.min - 1);
  1006. if (isFirstMatch(latestMatch, tokenGroup)) { //search for next possible match
  1007. if (qndx > (qt.quantifier.min - 1)) {
  1008. insertStop = true;
  1009. testPos = pos; //match the position after the group
  1010. break; //stop quantifierloop
  1011. } else return true;
  1012. } else {
  1013. return true;
  1014. }
  1015. }
  1016. }
  1017. } else {
  1018. match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  1019. if (match) return true;
  1020. }
  1021. }
  1022. else
  1023. testPos++;
  1024. }
  1025. for (var tndx = (ndxInitializer.length > 0 ? ndxInitializer.shift() : 0); tndx < maskToken.matches.length; tndx++) {
  1026. if (maskToken.matches[tndx].isQuantifier !== true) {
  1027. var match = handleMatch(maskToken.matches[tndx], [tndx].concat(loopNdx), quantifierRecurse);
  1028. if (match && testPos === pos) {
  1029. return match;
  1030. } else if (testPos > pos) {
  1031. break;
  1032. }
  1033. }
  1034. }
  1035. }
  1036. function mergeLocators(tests) {
  1037. var locator = [];
  1038. if (!$.isArray(tests)) tests = [tests];
  1039. if (tests.length > 0) {
  1040. if (tests[0].alternation === undefined) {
  1041. locator = determineTestTemplate(tests.slice()).locator.slice();
  1042. if (locator.length === 0) locator = tests[0].locator.slice();
  1043. }
  1044. else {
  1045. $.each(tests, function (ndx, tst) {
  1046. if (tst.def !== "") {
  1047. if (locator.length === 0) locator = tst.locator.slice();
  1048. else {
  1049. for (var i = 0; i < locator.length; i++) {
  1050. if (tst.locator[i] && locator[i].toString().indexOf(tst.locator[i]) === -1) {
  1051. locator[i] += "," + tst.locator[i];
  1052. }
  1053. }
  1054. }
  1055. }
  1056. });
  1057. }
  1058. }
  1059. return locator;
  1060. }
  1061. function filterTests(tests) {
  1062. if (opts.keepStatic && pos > 0) {
  1063. if (tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0)) {
  1064. if (tests[0].match.optionality !== true &&
  1065. tests[0].match.optionalQuantifier !== true &&
  1066. tests[0].match.fn === null && !/[0-9a-bA-Z]/.test(tests[0].match.def)) {
  1067. return [determineTestTemplate(tests)];
  1068. }
  1069. }
  1070. }
  1071. return tests;
  1072. }
  1073. if (pos > -1) {
  1074. if (ndxIntlzr === undefined) { //determine index initializer
  1075. var previousPos = pos - 1,
  1076. test;
  1077. while ((test = getMaskSet().validPositions[previousPos] || getMaskSet().tests[previousPos]) === undefined && previousPos > -1) {
  1078. previousPos--;
  1079. }
  1080. if (test !== undefined && previousPos > -1) {
  1081. ndxInitializer = mergeLocators(test);
  1082. cacheDependency = ndxInitializer.join("");
  1083. testPos = previousPos;
  1084. }
  1085. }
  1086. if (getMaskSet().tests[pos] && getMaskSet().tests[pos][0].cd === cacheDependency) { //cacheDependency is set on all tests, just check on the first
  1087. //console.log("cache hit " + pos + " - " + ndxIntlzr);
  1088. return filterTests(getMaskSet().tests[pos]);
  1089. }
  1090. for (var mtndx = ndxInitializer.shift(); mtndx < maskTokens.length; mtndx++) {
  1091. var match = resolveTestFromToken(maskTokens[mtndx], ndxInitializer, [mtndx]);
  1092. if ((match && testPos === pos) || testPos > pos) {
  1093. break;
  1094. }
  1095. }
  1096. }
  1097. if (matches.length === 0 || insertStop) {
  1098. matches.push({
  1099. match: {
  1100. fn: null,
  1101. cardinality: 0,
  1102. optionality: true,
  1103. casing: null,
  1104. def: "",
  1105. placeholder: ""
  1106. },
  1107. locator: [],
  1108. cd: cacheDependency
  1109. });
  1110. }
  1111. if (ndxIntlzr !== undefined && getMaskSet().tests[pos]) { //prioritize full tests for caching
  1112. return filterTests($.extend(true, [], matches));
  1113. }
  1114. getMaskSet().tests[pos] = $.extend(true, [], matches); //set a clone to prevent overwriting some props
  1115. // console.log(pos + " - " + JSON.stringify(matches));
  1116. return filterTests(getMaskSet().tests[pos]);
  1117. }
  1118. function getBufferTemplate() {
  1119. if (getMaskSet()._buffer === undefined) {
  1120. //generate template
  1121. getMaskSet()._buffer = getMaskTemplate(false, 1);
  1122. if (getMaskSet().buffer === undefined) {
  1123. getMaskSet()._buffer.slice();
  1124. }
  1125. }
  1126. return getMaskSet()._buffer;
  1127. }
  1128. function getBuffer(noCache) {
  1129. if (getMaskSet().buffer === undefined || noCache === true) {
  1130. getMaskSet().buffer = getMaskTemplate(true, getLastValidPosition(), true);
  1131. }
  1132. return getMaskSet().buffer;
  1133. }
  1134. function refreshFromBuffer(start, end, buffer) {
  1135. var i;
  1136. if (start === true) {
  1137. resetMaskSet();
  1138. start = 0;
  1139. end = buffer.length;
  1140. } else {
  1141. for (i = start; i < end; i++) {
  1142. delete getMaskSet().validPositions[i];
  1143. }
  1144. }
  1145. for (i = start; i < end; i++) {
  1146. resetMaskSet(true); //prevents clobber from the buffer
  1147. if (buffer[i] !== opts.skipOptionalPartCharacter) {
  1148. isValid(i, buffer[i], true, true);
  1149. }
  1150. }
  1151. }
  1152. function casing(elem, test, pos) {
  1153. switch (opts.casing || test.casing) {
  1154. case "upper":
  1155. elem = elem.toUpperCase();
  1156. break;
  1157. case "lower":
  1158. elem = elem.toLowerCase();
  1159. break;
  1160. case "title":
  1161. var posBefore = getMaskSet().validPositions[pos - 1];
  1162. if (pos === 0 || posBefore && posBefore.input === String.fromCharCode(Inputmask.keyCode.SPACE)) {
  1163. elem = elem.toUpperCase();
  1164. } else {
  1165. elem = elem.toLowerCase();
  1166. }
  1167. break;
  1168. }
  1169. return elem;
  1170. }
  1171. function checkAlternationMatch(altArr1, altArr2) {
  1172. var altArrC = opts.greedy ? altArr2 : altArr2.slice(0, 1),
  1173. isMatch = false;
  1174. for (var alndx = 0; alndx < altArr1.length; alndx++) {
  1175. if ($.inArray(altArr1[alndx], altArrC) !== -1) {
  1176. isMatch = true;
  1177. break;
  1178. }
  1179. }
  1180. return isMatch;
  1181. }
  1182. function isValid(pos, c, strict, fromSetValid, fromAlternate) { //strict true ~ no correction or autofill
  1183. function isSelection(posObj) {
  1184. var selection = isRTL ? (posObj.begin - posObj.end) > 1 || ((posObj.begin - posObj.end) === 1 && opts.insertMode) :
  1185. (posObj.end - posObj.begin) > 1 || ((posObj.end - posObj.begin) === 1 && opts.insertMode);
  1186. return selection && posObj.begin === 0 && posObj.end === getMaskSet().maskLength ? "full" : selection;
  1187. }
  1188. strict = strict === true; //always set a value to strict to prevent possible strange behavior in the extensions
  1189. var maskPos = pos;
  1190. if (pos.begin !== undefined) { //position was a position object - used to handle a delete by typing over a selection
  1191. maskPos = isRTL && !isSelection(pos) ? pos.end : pos.begin;
  1192. }
  1193. function _isValid(position, c, strict) {
  1194. var rslt = false;
  1195. $.each(getTests(position), function (ndx, tst) {
  1196. var test = tst.match,
  1197. loopend = c ? 1 : 0,
  1198. chrs = "";
  1199. for (var i = test.cardinality; i > loopend; i--) {
  1200. chrs += getBufferElement(position - (i - 1));
  1201. }
  1202. if (c) {
  1203. chrs += c;
  1204. }
  1205. //make sure the buffer is set and correct
  1206. getBuffer(true);
  1207. //return is false or a json object => { pos: ??, c: ??} or true
  1208. rslt = test.fn != null ?
  1209. test.fn.test(chrs, getMaskSet(), position, strict, opts, isSelection(pos)) : (c === test.def || c === opts.skipOptionalPartCharacter) && test.def !== "" ? //non mask
  1210. {
  1211. c: test.placeholder || test.def,
  1212. pos: position
  1213. } : false;
  1214. if (rslt !== false) {
  1215. var elem = rslt.c !== undefined ? rslt.c : c;
  1216. elem = (elem === opts.skipOptionalPartCharacter && test.fn === null) ? (test.placeholder || test.def) : elem;
  1217. var validatedPos = position,
  1218. possibleModifiedBuffer = getBuffer();
  1219. if (rslt.remove !== undefined) { //remove position(s)
  1220. if (!$.isArray(rslt.remove)) rslt.remove = [rslt.remove];
  1221. $.each(rslt.remove.sort(function (a, b) {
  1222. return b - a;
  1223. }), function (ndx, lmnt) {
  1224. stripValidPositions(lmnt, lmnt + 1, true);
  1225. });
  1226. }
  1227. if (rslt.insert !== undefined) { //insert position(s)
  1228. if (!$.isArray(rslt.insert)) rslt.insert = [rslt.insert];
  1229. $.each(rslt.insert.sort(function (a, b) {
  1230. return a - b;
  1231. }), function (ndx, lmnt) {
  1232. isValid(lmnt.pos, lmnt.c, true, fromSetValid);
  1233. });
  1234. }
  1235. if (rslt.refreshFromBuffer) {
  1236. var refresh = rslt.refreshFromBuffer;
  1237. strict = true;
  1238. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, possibleModifiedBuffer);
  1239. if (rslt.pos === undefined && rslt.c === undefined) {
  1240. rslt.pos = getLastValidPosition();
  1241. return false; //breakout if refreshFromBuffer && nothing to insert
  1242. }
  1243. validatedPos = rslt.pos !== undefined ? rslt.pos : position;
  1244. if (validatedPos !== position) {
  1245. rslt = $.extend(rslt, isValid(validatedPos, elem, true, fromSetValid)); //revalidate new position strict
  1246. return false;
  1247. }
  1248. } else if (rslt !== true && rslt.pos !== undefined && rslt.pos !== position) { //their is a position offset
  1249. validatedPos = rslt.pos;
  1250. refreshFromBuffer(position, validatedPos, getBuffer().slice());
  1251. if (validatedPos !== position) {
  1252. rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
  1253. return false;
  1254. }
  1255. }
  1256. if (rslt !== true && rslt.pos === undefined && rslt.c === undefined) {
  1257. return false; //breakout if nothing to insert
  1258. }
  1259. if (ndx > 0) {
  1260. resetMaskSet(true);
  1261. }
  1262. if (!setValidPosition(validatedPos, $.extend({}, tst, {
  1263. "input": casing(elem, test, validatedPos)
  1264. }), fromSetValid, isSelection(pos))) {
  1265. rslt = false;
  1266. }
  1267. return false; //break from $.each
  1268. }
  1269. }
  1270. );
  1271. return rslt;
  1272. }
  1273. function alternate(pos, c, strict) {
  1274. var validPsClone = $.extend(true, {}, getMaskSet().validPositions),
  1275. lastAlt,
  1276. alternation,
  1277. isValidRslt = false,
  1278. altPos, prevAltPos, i, validPos, lAltPos = getLastValidPosition(), altNdxs, decisionPos;
  1279. //find last modified alternation
  1280. prevAltPos = getMaskSet().validPositions[lAltPos];
  1281. for (; lAltPos >= 0; lAltPos--) {
  1282. altPos = getMaskSet().validPositions[lAltPos];
  1283. if (altPos && altPos.alternation !== undefined) {
  1284. lastAlt = lAltPos;
  1285. alternation = getMaskSet().validPositions[lastAlt].alternation;
  1286. if (prevAltPos.locator[altPos.alternation] !== altPos.locator[altPos.alternation]) {
  1287. break;
  1288. }
  1289. prevAltPos = altPos;
  1290. }
  1291. }
  1292. if (alternation !== undefined) {
  1293. decisionPos = parseInt(lastAlt);
  1294. var decisionTaker = prevAltPos.locator[prevAltPos.alternation || alternation] !== undefined ? prevAltPos.locator[prevAltPos.alternation || alternation] : altNdxs[0]; //no match in the alternations (length mismatch)
  1295. if (decisionTaker.length > 0) { //no decision taken ~ take first one as decider
  1296. decisionTaker = decisionTaker.split(",")[0];
  1297. }
  1298. var possibilityPos = getMaskSet().validPositions[decisionPos], prevPos = getMaskSet().validPositions[decisionPos - 1];
  1299. $.each(getTests(decisionPos, prevPos ? prevPos.locator : undefined, decisionPos - 1), function (ndx, test) {
  1300. altNdxs = test.locator[alternation] ? test.locator[alternation].toString().split(",") : [];
  1301. for (var mndx = 0; mndx < altNdxs.length; mndx++) {
  1302. var validInputs = [],
  1303. staticInputsBeforePos = 0,
  1304. staticInputsBeforePosAlternate = 0,
  1305. verifyValidInput = false;
  1306. if (decisionTaker < altNdxs[mndx] && (test.na === undefined || $.inArray(altNdxs[mndx], test.na.split(",")) === -1)) {
  1307. getMaskSet().validPositions[decisionPos] = $.extend(true, {}, test);
  1308. var possibilities = getMaskSet().validPositions[decisionPos].locator;
  1309. getMaskSet().validPositions[decisionPos].locator[alternation] = parseInt(altNdxs[mndx]); //set forced decision
  1310. if (test.match.fn == null) {
  1311. if (possibilityPos.input !== test.match.def) {
  1312. verifyValidInput = true; //verify that the new definition matches the input
  1313. if (possibilityPos.generatedInput !== true) {
  1314. validInputs.push(possibilityPos.input);
  1315. }
  1316. }
  1317. staticInputsBeforePosAlternate++;
  1318. getMaskSet().validPositions[decisionPos].generatedInput = !/[0-9a-bA-Z]/.test(test.match.def);
  1319. getMaskSet().validPositions[decisionPos].input = test.match.def;
  1320. } else {
  1321. getMaskSet().validPositions[decisionPos].input = possibilityPos.input;
  1322. }
  1323. for (i = decisionPos + 1; i < getLastValidPosition(undefined, true) + 1; i++) {
  1324. validPos = getMaskSet().validPositions[i];
  1325. if (validPos && validPos.generatedInput !== true && /[0-9a-bA-Z]/.test(validPos.input)) {
  1326. validInputs.push(validPos.input);
  1327. } else if (i < pos) staticInputsBeforePos++;
  1328. delete getMaskSet().validPositions[i];
  1329. }
  1330. if (verifyValidInput && validInputs[0] === test.match.def) {
  1331. validInputs.shift();
  1332. }
  1333. resetMaskSet(true); //clear getbuffer
  1334. isValidRslt = true;
  1335. while (validInputs.length > 0) {
  1336. var input = validInputs.shift();
  1337. if (input !== opts.skipOptionalPartCharacter) {
  1338. if (!(isValidRslt = isValid(getLastValidPosition(undefined, true) + 1, input, false, fromSetValid, true))) {
  1339. break;
  1340. }
  1341. }
  1342. }
  1343. if (isValidRslt) {
  1344. getMaskSet().validPositions[decisionPos].locator = possibilities; //reset forceddecision ~ needed for proper delete
  1345. var targetLvp = getLastValidPosition(pos) + 1;
  1346. for (i = decisionPos + 1; i < getLastValidPosition() + 1; i++) {
  1347. validPos = getMaskSet().validPositions[i];
  1348. if ((validPos === undefined || validPos.match.fn == null) && i < (pos + (staticInputsBeforePosAlternate - staticInputsBeforePos))) {
  1349. staticInputsBeforePosAlternate++;
  1350. }
  1351. }
  1352. pos = pos + (staticInputsBeforePosAlternate - staticInputsBeforePos);
  1353. isValidRslt = isValid(pos > targetLvp ? targetLvp : pos, c, strict, fromSetValid, true);
  1354. }
  1355. if (!isValidRslt) {
  1356. resetMaskSet();
  1357. getMaskSet().validPositions = $.extend(true, {}, validPsClone);
  1358. } else return false; //exit $.each
  1359. }
  1360. }
  1361. });
  1362. }
  1363. return isValidRslt;
  1364. }
  1365. //set alternator choice on previous skipped placeholder positions
  1366. function trackbackAlternations(originalPos, newPos) {
  1367. var vp = getMaskSet().validPositions[newPos];
  1368. if (vp) {
  1369. var targetLocator = vp.locator,
  1370. tll = targetLocator.length;
  1371. for (var ps = originalPos; ps < newPos; ps++) {
  1372. if (getMaskSet().validPositions[ps] === undefined && !isMask(ps, true)) {
  1373. var tests = getTests(ps),
  1374. bestMatch = tests[0],
  1375. equality = -1;
  1376. $.each(tests, function (ndx, tst) { //find best matching
  1377. for (var i = 0; i < tll; i++) {
  1378. if (tst.locator[i] !== undefined && checkAlternationMatch(tst.locator[i].toString().split(","), targetLocator[i].toString().split(","))) {
  1379. if (equality < i) {
  1380. equality = i;
  1381. bestMatch = tst;
  1382. }
  1383. } else break;
  1384. }
  1385. });
  1386. setValidPosition(ps, $.extend({}, bestMatch, {
  1387. "input": bestMatch.match.placeholder || bestMatch.match.def
  1388. }), true);
  1389. }
  1390. }
  1391. }
  1392. }
  1393. function setValidPosition(pos, validTest, fromSetValid, isSelection) {
  1394. if (isSelection || (opts.insertMode && getMaskSet().validPositions[pos] !== undefined && fromSetValid === undefined)) {
  1395. //reposition & revalidate others
  1396. var positionsClone = $.extend(true, {}, getMaskSet().validPositions),
  1397. lvp = getLastValidPosition(undefined, true),
  1398. i;
  1399. for (i = pos; i <= lvp; i++) { //clear selection
  1400. delete getMaskSet().validPositions[i];
  1401. }
  1402. getMaskSet().validPositions[pos] = $.extend(true, {}, validTest);
  1403. var valid = true,
  1404. j, vps = getMaskSet().validPositions, needsValidation = false,
  1405. initialLength = getMaskSet().maskLength;
  1406. for (i = (j = pos); i <= lvp; i++) {
  1407. var t = positionsClone[i];
  1408. if (t !== undefined /*&& (t.generatedInput !== true || t.match.fn === null)*/) {
  1409. var posMatch = j;
  1410. while (posMatch < getMaskSet().maskLength && ((t.match.fn === null && vps[i] && (vps[i].match.optionalQuantifier === true || vps[i].match.optionality === true)) || t.match.fn != null)) {
  1411. posMatch++;
  1412. if (needsValidation === false && positionsClone[posMatch] && positionsClone[posMatch].match.def === t.match.def) { //obvious match
  1413. getMaskSet().validPositions[posMatch] = $.extend(true, {}, positionsClone[posMatch]);
  1414. getMaskSet().validPositions[posMatch].input = t.input;
  1415. fillMissingNonMask(posMatch);
  1416. j = posMatch;
  1417. valid = true;
  1418. } else if (positionCanMatchDefinition(posMatch, t.match.def)) { //validated match
  1419. var result = isValid(posMatch, t.input, true, true);
  1420. valid = result !== false;
  1421. j = (result.caret || result.insert) ? getLastValidPosition() : posMatch;
  1422. needsValidation = true;
  1423. } else {
  1424. valid = t.generatedInput === true;
  1425. }
  1426. if (getMaskSet().maskLength < initialLength) getMaskSet().maskLength = initialLength; //a bit hacky but the masklength is corrected later on
  1427. if (valid) break;
  1428. }
  1429. }
  1430. if (!valid) break;
  1431. }
  1432. if (!valid) {
  1433. getMaskSet().validPositions = $.extend(true, {}, positionsClone);
  1434. resetMaskSet(true);
  1435. return false;
  1436. }
  1437. }
  1438. else
  1439. getMaskSet().validPositions[pos] = $.extend(true, {}, validTest);
  1440. ;
  1441. resetMaskSet(true);
  1442. return true;
  1443. }
  1444. function fillMissingNonMask(maskPos) {
  1445. //Check for a nonmask before the pos
  1446. //find previous valid
  1447. for (var pndx = maskPos - 1; pndx > -1; pndx--) {
  1448. if (getMaskSet().validPositions[pndx]) break;
  1449. }
  1450. ////fill missing nonmask and valid placeholders
  1451. var testTemplate, testsFromPos;
  1452. for (pndx++; pndx < maskPos; pndx++) {
  1453. if (getMaskSet().validPositions[pndx] === undefined && (opts.jitMasking === false || opts.jitMasking > pndx)) {
  1454. testsFromPos = getTests(pndx, getTestTemplate(pndx - 1).locator, pndx - 1).slice();
  1455. if (testsFromPos[testsFromPos.length - 1].match.def === "") testsFromPos.pop();
  1456. testTemplate = determineTestTemplate(testsFromPos);
  1457. if (testTemplate && (testTemplate.match.def === opts.radixPointDefinitionSymbol || !isMask(pndx, true) ||
  1458. ($.inArray(opts.radixPoint, getBuffer()) < pndx && testTemplate.match.fn && testTemplate.match.fn.test(getPlaceholder(pndx), getMaskSet(), pndx, false, opts)))) {
  1459. result = _isValid(pndx, testTemplate.match.placeholder || (testTemplate.match.fn == null ? testTemplate.match.def : (getPlaceholder(pndx) !== "" ? getPlaceholder(pndx) : getBuffer()[pndx])), true);
  1460. if (result !== false) {
  1461. getMaskSet().validPositions[result.pos || pndx].generatedInput = true;
  1462. }
  1463. }
  1464. }
  1465. }
  1466. }
  1467. var result = false,
  1468. positionsClone = $.extend(true, {}, getMaskSet().validPositions); //clone the currentPositions
  1469. fillMissingNonMask(maskPos);
  1470. if (isSelection(pos)) {
  1471. handleRemove(undefined, Inputmask.keyCode.DELETE, pos);
  1472. maskPos = getMaskSet().p;
  1473. }
  1474. if (maskPos < getMaskSet().maskLength) {
  1475. result = _isValid(maskPos, c, strict);
  1476. if ((!strict || fromSetValid === true) && result === false) {
  1477. var currentPosValid = getMaskSet().validPositions[maskPos];
  1478. if (currentPosValid && currentPosValid.match.fn === null && (currentPosValid.match.def === c || c === opts.skipOptionalPartCharacter)) {
  1479. result = {
  1480. "caret": seekNext(maskPos)
  1481. };
  1482. } else if ((opts.insertMode || getMaskSet().validPositions[seekNext(maskPos)] === undefined) && !isMask(maskPos, true)) { //does the input match on a further position?
  1483. var testsFromPos = getTests(maskPos).slice();
  1484. if (testsFromPos[testsFromPos.length - 1].match.def === "") testsFromPos.pop();
  1485. var staticChar = determineTestTemplate(testsFromPos, true);
  1486. if (staticChar && staticChar.match.fn === null) {
  1487. staticChar = staticChar.match.placeholder || staticChar.match.def;
  1488. _isValid(maskPos, staticChar, strict);
  1489. getMaskSet().validPositions[maskPos].generatedInput = true;
  1490. }
  1491. for (var nPos = maskPos + 1, snPos = seekNext(maskPos); nPos <= snPos; nPos++) {
  1492. result = _isValid(nPos, c, strict);
  1493. if (result !== false) {
  1494. trackbackAlternations(maskPos, result.pos !== undefined ? result.pos : nPos);
  1495. maskPos = nPos;
  1496. break;
  1497. }
  1498. }
  1499. }
  1500. }
  1501. }
  1502. if (result === false && opts.keepStatic && !strict && fromAlternate !== true) { //try fuzzy alternator logic
  1503. result = alternate(maskPos, c, strict);
  1504. }
  1505. if (result === true) {
  1506. result = {
  1507. "pos": maskPos
  1508. };
  1509. }
  1510. if ($.isFunction(opts.postValidation) && result !== false && !strict && fromSetValid !== true) {
  1511. result = opts.postValidation(getBuffer(true), result, opts) ? result : false;
  1512. }
  1513. if (result.pos === undefined) {
  1514. result.pos = maskPos;
  1515. }
  1516. if (result === false) {
  1517. resetMaskSet(true);
  1518. getMaskSet().validPositions = $.extend(true, {}, positionsClone); //revert validation changes
  1519. }
  1520. return result;
  1521. }
  1522. function isMask(pos, strict) {
  1523. var test;
  1524. if (strict) {
  1525. test = getTestTemplate(pos).match;
  1526. if (test.def === "") test = getTest(pos).match;
  1527. } else test = getTest(pos).match;
  1528. if (test.fn != null) {
  1529. return test.fn;
  1530. } else if (strict !== true && pos > -1) {
  1531. var tests = getTests(pos);
  1532. return tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0);
  1533. }
  1534. return false;
  1535. }
  1536. function seekNext(pos, newBlock) {
  1537. var maskL = getMaskSet().maskLength;
  1538. if (pos >= maskL) return maskL;
  1539. var position = pos;
  1540. while (++position < maskL &&
  1541. ((newBlock === true && (getTest(position).match.newBlockMarker !== true || !isMask(position))) ||
  1542. (newBlock !== true && !isMask(position)))) {
  1543. }
  1544. return position;
  1545. }
  1546. function seekPrevious(pos, newBlock) {
  1547. var position = pos, tests;
  1548. if (position <= 0) return 0;
  1549. while (--position > 0 &&
  1550. ((newBlock === true && getTest(position).match.newBlockMarker !== true) ||
  1551. (newBlock !== true && !isMask(position) &&
  1552. (tests = getTests(position), tests.length < 2 || (tests.length === 2 && tests[1].match.def === ""))))) {
  1553. }
  1554. return position;
  1555. }
  1556. function getBufferElement(position) {
  1557. return getMaskSet().validPositions[position] === undefined ? getPlaceholder(position) : getMaskSet().validPositions[position].input;
  1558. }
  1559. function writeBuffer(input, buffer, caretPos, event, triggerInputEvent) {
  1560. if (event && $.isFunction(opts.onBeforeWrite)) {
  1561. var result = opts.onBeforeWrite(event, buffer, caretPos, opts);
  1562. if (result) {
  1563. if (result.refreshFromBuffer) {
  1564. var refresh = result.refreshFromBuffer;
  1565. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer || buffer);
  1566. buffer = getBuffer(true);
  1567. }
  1568. //only alter when intented !== undefined
  1569. if (caretPos !== undefined) caretPos = result.caret !== undefined ? result.caret : caretPos;
  1570. }
  1571. }
  1572. input.inputmask._valueSet(buffer.join(""));
  1573. if (caretPos !== undefined && (event === undefined || event.type !== "blur")) {
  1574. caret(input, caretPos);
  1575. } else renderColorMask(input, buffer, caretPos);
  1576. if (triggerInputEvent === true) {
  1577. skipInputEvent = true;
  1578. $(input).trigger("input");
  1579. }
  1580. }
  1581. function getPlaceholder(pos, test) {
  1582. test = test || getTest(pos).match;
  1583. if (test.placeholder !== undefined) {
  1584. return test.placeholder;
  1585. } else if (test.fn === null) {
  1586. if (pos > -1 && getMaskSet().validPositions[pos] === undefined) {
  1587. var tests = getTests(pos),
  1588. staticAlternations = [],
  1589. prevTest;
  1590. if (tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0)) {
  1591. for (var i = 0; i < tests.length; i++) {
  1592. if (tests[i].match.optionality !== true && tests[i].match.optionalQuantifier !== true &&
  1593. (tests[i].match.fn === null || (prevTest === undefined || tests[i].match.fn.test(prevTest.match.def, getMaskSet(), pos, true, opts) !== false))) {
  1594. staticAlternations.push(tests[i]);
  1595. if (tests[i].match.fn === null) prevTest = tests[i];
  1596. if (staticAlternations.length > 1) {
  1597. if (/[0-9a-bA-Z]/.test(staticAlternations[0].match.def)) {
  1598. return opts.placeholder.charAt(pos % opts.placeholder.length);
  1599. }
  1600. }
  1601. }
  1602. }
  1603. }
  1604. }
  1605. return test.def;
  1606. }
  1607. return opts.placeholder.charAt(pos % opts.placeholder.length);
  1608. }
  1609. function checkVal(input, writeOut, strict, nptvl, initiatingEvent, stickyCaret) {
  1610. var inputValue = nptvl.slice(),
  1611. charCodes = "",
  1612. initialNdx = 0, result = undefined;
  1613. function isTemplateMatch() {
  1614. var isMatch = false;
  1615. var charCodeNdx = getBufferTemplate().slice(initialNdx, seekNext(initialNdx)).join("").indexOf(charCodes);
  1616. if (charCodeNdx !== -1 && !isMask(initialNdx)) {
  1617. isMatch = true;
  1618. var bufferTemplateArr = getBufferTemplate().slice(initialNdx, initialNdx + charCodeNdx);
  1619. for (var i = 0; i < bufferTemplateArr.length; i++) {
  1620. if (bufferTemplateArr[i] !== " ") {
  1621. isMatch = false;
  1622. break;
  1623. }
  1624. }
  1625. }
  1626. return isMatch;
  1627. }
  1628. resetMaskSet();
  1629. getMaskSet().p = seekNext(-1);
  1630. // if (writeOut) input.inputmask._valueSet(""); //initial clear
  1631. if (!strict) {
  1632. if (opts.autoUnmask !== true) {
  1633. var staticInput = getBufferTemplate().slice(0, seekNext(-1)).join(""),
  1634. matches = inputValue.join("").match(new RegExp("^" + Inputmask.escapeRegex(staticInput), "g"));
  1635. if (matches && matches.length > 0) {
  1636. inputValue.splice(0, matches.length * staticInput.length);
  1637. initialNdx = seekNext(initialNdx);
  1638. }
  1639. } else {
  1640. initialNdx = seekNext(initialNdx);
  1641. }
  1642. }
  1643. $.each(inputValue, function (ndx, charCode) {
  1644. if (charCode !== undefined) { //inputfallback strips some elements out of the inputarray. $.each logically presents them as undefined
  1645. var keypress = new $.Event("keypress");
  1646. keypress.which = charCode.charCodeAt(0);
  1647. charCodes += charCode;
  1648. var lvp = getLastValidPosition(undefined, true),
  1649. lvTest = getMaskSet().validPositions[lvp],
  1650. nextTest = getTestTemplate(lvp + 1, lvTest ? lvTest.locator.slice() : undefined, lvp);
  1651. if (!isTemplateMatch() || strict || opts.autoUnmask) {
  1652. var pos = strict ? ndx : (nextTest.match.fn == null && nextTest.match.optionality && (lvp + 1) < getMaskSet().p ? lvp + 1 : getMaskSet().p);
  1653. result = EventHandlers.keypressEvent.call(input, keypress, true, false, strict, pos);
  1654. initialNdx = pos + 1;
  1655. charCodes = "";
  1656. } else {
  1657. result = EventHandlers.keypressEvent.call(input, keypress, true, false, true, lvp + 1);
  1658. }
  1659. if (!strict && $.isFunction(opts.onBeforeWrite)) {
  1660. result = opts.onBeforeWrite(keypress, getBuffer(), result.forwardPosition, opts);
  1661. if (result && result.refreshFromBuffer) {
  1662. var refresh = result.refreshFromBuffer;
  1663. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer);
  1664. resetMaskSet(true);
  1665. if (result.caret) {
  1666. getMaskSet().p = result.caret;
  1667. }
  1668. }
  1669. }
  1670. }
  1671. });
  1672. if (writeOut) {
  1673. var caretPos = undefined, lvp = getLastValidPosition();
  1674. if (document.activeElement === input && (initiatingEvent || result)) {
  1675. caretPos = caret(input).begin;
  1676. if (initiatingEvent && result === false) caretPos = seekNext(getLastValidPosition(caretPos));
  1677. if (result && stickyCaret !== true && (caretPos < lvp + 1 || lvp === -1))
  1678. caretPos = (opts.numericInput && result.caret === undefined) ? seekPrevious(result.forwardPosition) : result.forwardPosition;
  1679. }
  1680. writeBuffer(input, getBuffer(), caretPos, initiatingEvent || new $.Event("checkval"));
  1681. }
  1682. }
  1683. function unmaskedvalue(input) {
  1684. if (input && input.inputmask === undefined) {
  1685. return input.value;
  1686. }
  1687. var umValue = [],
  1688. vps = getMaskSet().validPositions;
  1689. for (var pndx in vps) {
  1690. if (vps[pndx].match && vps[pndx].match.fn != null) {
  1691. umValue.push(vps[pndx].input);
  1692. }
  1693. }
  1694. var unmaskedValue = umValue.length === 0 ? "" : (isRTL ? umValue.reverse() : umValue).join("");
  1695. if ($.isFunction(opts.onUnMask)) {
  1696. var bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join("");
  1697. unmaskedValue = (opts.onUnMask(bufferValue, unmaskedValue, opts) || unmaskedValue);
  1698. }
  1699. return unmaskedValue;
  1700. }
  1701. function caret(input, begin, end, notranslate) {
  1702. function translatePosition(pos) {
  1703. if (notranslate !== true && isRTL && typeof pos === "number" && (!opts.greedy || opts.placeholder !== "")) {
  1704. 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)
  1705. pos = bffrLght - pos;
  1706. }
  1707. return pos;
  1708. }
  1709. var range;
  1710. if (typeof begin === "number") {
  1711. begin = translatePosition(begin);
  1712. end = translatePosition(end);
  1713. end = (typeof end == "number") ? end : begin;
  1714. // if (!$(input).is(":visible")) {
  1715. // return;
  1716. // }
  1717. var scrollCalc = parseInt(((input.ownerDocument.defaultView || window).getComputedStyle ? (input.ownerDocument.defaultView || window).getComputedStyle(input, null) : input.currentStyle).fontSize) * end;
  1718. input.scrollLeft = scrollCalc > input.scrollWidth ? scrollCalc : 0;
  1719. if (!mobile && opts.insertMode === false && begin === end) end++; //set visualization for insert/overwrite mode
  1720. if (input.setSelectionRange) {
  1721. input.selectionStart = begin;
  1722. input.selectionEnd = end;
  1723. } else if (window.getSelection) {
  1724. range = document.createRange();
  1725. if (input.firstChild === undefined || input.firstChild === null) {
  1726. var textNode = document.createTextNode("");
  1727. input.appendChild(textNode);
  1728. }
  1729. range.setStart(input.firstChild, begin < input.inputmask._valueGet().length ? begin : input.inputmask._valueGet().length);
  1730. range.setEnd(input.firstChild, end < input.inputmask._valueGet().length ? end : input.inputmask._valueGet().length);
  1731. range.collapse(true);
  1732. var sel = window.getSelection();
  1733. sel.removeAllRanges();
  1734. sel.addRange(range);
  1735. //input.focus();
  1736. } else if (input.createTextRange) {
  1737. range = input.createTextRange();
  1738. range.collapse(true);
  1739. range.moveEnd("character", end);
  1740. range.moveStart("character", begin);
  1741. range.select();
  1742. }
  1743. renderColorMask(input, undefined, {begin: begin, end: end});
  1744. } else {
  1745. if (input.setSelectionRange) {
  1746. begin = input.selectionStart;
  1747. end = input.selectionEnd;
  1748. } else if (window.getSelection) {
  1749. range = window.getSelection().getRangeAt(0);
  1750. if (range.commonAncestorContainer.parentNode === input || range.commonAncestorContainer === input) {
  1751. begin = range.startOffset;
  1752. end = range.endOffset;
  1753. }
  1754. } else if (document.selection && document.selection.createRange) {
  1755. range = document.selection.createRange();
  1756. begin = 0 - range.duplicate().moveStart("character", -input.inputmask._valueGet().length);
  1757. end = begin + range.text.length;
  1758. }
  1759. /*eslint-disable consistent-return */
  1760. return {
  1761. "begin": translatePosition(begin),
  1762. "end": translatePosition(end)
  1763. };
  1764. /*eslint-enable consistent-return */
  1765. }
  1766. }
  1767. function determineLastRequiredPosition(returnDefinition) {
  1768. var buffer = getBuffer(),
  1769. bl = buffer.length,
  1770. pos, lvp = getLastValidPosition(),
  1771. positions = {},
  1772. lvTest = getMaskSet().validPositions[lvp],
  1773. ndxIntlzr = lvTest !== undefined ? lvTest.locator.slice() : undefined,
  1774. testPos;
  1775. for (pos = lvp + 1; pos < buffer.length; pos++) {
  1776. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  1777. ndxIntlzr = testPos.locator.slice();
  1778. positions[pos] = $.extend(true, {}, testPos);
  1779. }
  1780. var lvTestAlt = lvTest && lvTest.alternation !== undefined ? lvTest.locator[lvTest.alternation] : undefined;
  1781. for (pos = bl - 1; pos > lvp; pos--) {
  1782. testPos = positions[pos];
  1783. if ((testPos.match.optionality ||
  1784. testPos.match.optionalQuantifier ||
  1785. (lvTestAlt &&
  1786. ((lvTestAlt !== positions[pos].locator[lvTest.alternation] && testPos.match.fn != null) ||
  1787. (testPos.match.fn === null && testPos.locator[lvTest.alternation] && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAlt.toString().split(",")) && getTests(pos)[0].def !== "")))) &&
  1788. 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. validPos, bl = buffer.length;
  1800. while (rl < bl && !isMask(rl + 1) && (validPos = getTest(rl + 1)) && validPos.match.optionality !== true && validPos.match.optionalQuantifier !== true) {
  1801. rl++;
  1802. }
  1803. while ((validPos = getTest(rl - 1)) && validPos.match.optionality && validPos.input === opts.skipOptionalPartCharacter) {
  1804. rl--;
  1805. }
  1806. buffer.splice(rl);
  1807. return buffer;
  1808. }
  1809. function isComplete(buffer) { //return true / false / undefined (repeat *)
  1810. if ($.isFunction(opts.isComplete)) return opts.isComplete(buffer, opts);
  1811. if (opts.repeat === "*") return undefined;
  1812. var complete = false,
  1813. lrp = determineLastRequiredPosition(true),
  1814. aml = seekPrevious(lrp.l);
  1815. if (lrp.def === undefined || lrp.def.newBlockMarker || lrp.def.optionality || lrp.def.optionalQuantifier) {
  1816. complete = true;
  1817. for (var i = 0; i <= aml; i++) {
  1818. var test = getTestTemplate(i).match;
  1819. if ((test.fn !== null && getMaskSet().validPositions[i] === undefined && test.optionality !== true && test.optionalQuantifier !== true) || (test.fn === null && buffer[i] !== getPlaceholder(i, test))) {
  1820. complete = false;
  1821. break;
  1822. }
  1823. }
  1824. }
  1825. return complete;
  1826. }
  1827. function handleRemove(input, k, pos, strict) {
  1828. function generalize() {
  1829. if (opts.keepStatic) {
  1830. var validInputs = [],
  1831. lastAlt = getLastValidPosition(-1, true), positionsClone = $.extend(true, {}, getMaskSet().validPositions),
  1832. prevAltPos = getMaskSet().validPositions[lastAlt];
  1833. //find last alternation
  1834. for (; lastAlt >= 0; lastAlt--) {
  1835. var altPos = getMaskSet().validPositions[lastAlt];
  1836. if (altPos) {
  1837. if (altPos.generatedInput !== true && /[0-9a-bA-Z]/.test(altPos.input)) {
  1838. validInputs.push(altPos.input);
  1839. }
  1840. delete getMaskSet().validPositions[lastAlt];
  1841. if (altPos.alternation !== undefined && altPos.locator[altPos.alternation] !== prevAltPos.locator[altPos.alternation]) {
  1842. break;
  1843. }
  1844. prevAltPos = altPos;
  1845. }
  1846. }
  1847. if (lastAlt > -1) {
  1848. getMaskSet().p = seekNext(getLastValidPosition(-1, true));
  1849. while (validInputs.length > 0) {
  1850. var keypress = new $.Event("keypress");
  1851. keypress.which = validInputs.pop().charCodeAt(0);
  1852. EventHandlers.keypressEvent.call(input, keypress, true, false, false, getMaskSet().p);
  1853. }
  1854. } else getMaskSet().validPositions = $.extend(true, {}, positionsClone); //restore original positions
  1855. }
  1856. }
  1857. if (opts.numericInput || isRTL) {
  1858. if (k === Inputmask.keyCode.BACKSPACE) {
  1859. k = Inputmask.keyCode.DELETE;
  1860. } else if (k === Inputmask.keyCode.DELETE) {
  1861. k = Inputmask.keyCode.BACKSPACE;
  1862. }
  1863. if (isRTL) {
  1864. var pend = pos.end;
  1865. pos.end = pos.begin;
  1866. pos.begin = pend;
  1867. }
  1868. }
  1869. if (k === Inputmask.keyCode.BACKSPACE && (pos.end - pos.begin < 1 || opts.insertMode === false)) {
  1870. pos.begin = seekPrevious(pos.begin);
  1871. if (getMaskSet().validPositions[pos.begin] !== undefined && (getMaskSet().validPositions[pos.begin].input === opts.groupSeparator || getMaskSet().validPositions[pos.begin].input === opts.radixPoint)) {
  1872. pos.begin--;
  1873. }
  1874. } else if (k === Inputmask.keyCode.DELETE && pos.begin === pos.end) {
  1875. pos.end = isMask(pos.end, true) ? pos.end + 1 : seekNext(pos.end) + 1;
  1876. if (getMaskSet().validPositions[pos.begin] !== undefined && (getMaskSet().validPositions[pos.begin].input === opts.groupSeparator || getMaskSet().validPositions[pos.begin].input === opts.radixPoint)) {
  1877. pos.end++;
  1878. }
  1879. }
  1880. stripValidPositions(pos.begin, pos.end, false, strict);
  1881. if (strict !== true) {
  1882. generalize(); //revert the alternation
  1883. }
  1884. var lvp = getLastValidPosition(pos.begin, true);
  1885. if (lvp < pos.begin) {
  1886. //if (lvp === -1) resetMaskSet();
  1887. getMaskSet().p = seekNext(lvp);
  1888. } else if (strict !== true) {
  1889. getMaskSet().p = pos.begin;
  1890. }
  1891. }
  1892. var EventRuler = {
  1893. on: function (input, eventName, eventHandler) {
  1894. var ev = function (e) {
  1895. // console.log("triggered " + e.type);
  1896. if (this.inputmask === undefined && this.nodeName !== "FORM") { //happens when cloning an object with jquery.clone
  1897. var imOpts = $.data(this, "_inputmask_opts");
  1898. if (imOpts) (new Inputmask(imOpts)).mask(this);
  1899. else EventRuler.off(this);
  1900. } else if (e.type !== "setvalue" && this.nodeName !== "FORM" && (this.disabled || (this.readOnly && !(e.type === "keydown" && (e.ctrlKey && e.keyCode === 67) || (opts.tabThrough === false && e.keyCode === Inputmask.keyCode.TAB))))) {
  1901. e.preventDefault();
  1902. } else {
  1903. switch (e.type) {
  1904. case "input":
  1905. if (skipInputEvent === true) {
  1906. skipInputEvent = false;
  1907. return e.preventDefault();
  1908. }
  1909. break;
  1910. case "keydown":
  1911. //Safari 5.1.x - modal dialog fires keypress twice workaround
  1912. skipKeyPressEvent = false;
  1913. skipInputEvent = false;
  1914. break;
  1915. case "keypress":
  1916. if (skipKeyPressEvent === true) {
  1917. return e.preventDefault();
  1918. }
  1919. skipKeyPressEvent = true;
  1920. break;
  1921. case "click":
  1922. if (iemobile || iphone) {
  1923. var that = this, args = arguments;
  1924. setTimeout(function () {
  1925. eventHandler.apply(that, args);
  1926. }, 0);
  1927. return false;
  1928. }
  1929. break;
  1930. }
  1931. // console.log("executed " + e.type);
  1932. var returnVal = eventHandler.apply(this, arguments);
  1933. if (returnVal === false) {
  1934. e.preventDefault();
  1935. e.stopPropagation();
  1936. }
  1937. return returnVal;
  1938. }
  1939. };
  1940. //keep instance of the event
  1941. input.inputmask.events[eventName] = input.inputmask.events[eventName] || [];
  1942. input.inputmask.events[eventName].push(ev);
  1943. if ($.inArray(eventName, ["submit", "reset"]) !== -1) {
  1944. if (input.form != null) $(input.form).on(eventName, ev);
  1945. } else {
  1946. $(input).on(eventName, ev);
  1947. }
  1948. },
  1949. off: function (input, event) {
  1950. if (input.inputmask && input.inputmask.events) {
  1951. var events;
  1952. if (event) {
  1953. events = [];
  1954. events[event] = input.inputmask.events[event];
  1955. } else {
  1956. events = input.inputmask.events;
  1957. }
  1958. $.each(events, function (eventName, evArr) {
  1959. while (evArr.length > 0) {
  1960. var ev = evArr.pop();
  1961. if ($.inArray(eventName, ["submit", "reset"]) !== -1) {
  1962. if (input.form != null) $(input.form).off(eventName, ev);
  1963. } else {
  1964. $(input).off(eventName, ev);
  1965. }
  1966. }
  1967. delete input.inputmask.events[eventName];
  1968. });
  1969. }
  1970. }
  1971. };
  1972. var EventHandlers = {
  1973. keydownEvent: function (e) {
  1974. function isInputEventSupported(eventName) {
  1975. var el = document.createElement("input"),
  1976. evName = "on" + eventName,
  1977. isSupported = (evName in el);
  1978. if (!isSupported) {
  1979. el.setAttribute(evName, "return;");
  1980. isSupported = typeof el[evName] == "function";
  1981. }
  1982. el = null;
  1983. return isSupported;
  1984. }
  1985. var input = this,
  1986. $input = $(input),
  1987. k = e.keyCode,
  1988. pos = caret(input);
  1989. //backspace, delete, and escape get special treatment
  1990. 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
  1991. e.preventDefault(); //stop default action but allow propagation
  1992. handleRemove(input, k, pos);
  1993. writeBuffer(input, getBuffer(true), getMaskSet().p, e, input.inputmask._valueGet() !== getBuffer().join(""));
  1994. if (input.inputmask._valueGet() === getBufferTemplate().join("")) {
  1995. $input.trigger("cleared");
  1996. } else if (isComplete(getBuffer()) === true) {
  1997. $input.trigger("complete");
  1998. }
  1999. } else if (k === Inputmask.keyCode.END || k === Inputmask.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  2000. e.preventDefault();
  2001. var caretPos = seekNext(getLastValidPosition());
  2002. if (!opts.insertMode && caretPos === getMaskSet().maskLength && !e.shiftKey) caretPos--;
  2003. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos, true);
  2004. } else if ((k === Inputmask.keyCode.HOME && !e.shiftKey) || k === Inputmask.keyCode.PAGE_UP) { //Home or page_up
  2005. e.preventDefault();
  2006. caret(input, 0, e.shiftKey ? pos.begin : 0, true);
  2007. } else if (((opts.undoOnEscape && k === Inputmask.keyCode.ESCAPE) || (k === 90 && e.ctrlKey)) && e.altKey !== true) { //escape && undo && #762
  2008. checkVal(input, true, false, undoValue.split(""));
  2009. $input.trigger("click");
  2010. } else if (k === Inputmask.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
  2011. opts.insertMode = !opts.insertMode;
  2012. caret(input, !opts.insertMode && pos.begin === getMaskSet().maskLength ? pos.begin - 1 : pos.begin);
  2013. } else if (opts.tabThrough === true && k === Inputmask.keyCode.TAB) {
  2014. if (e.shiftKey === true) {
  2015. if (getTest(pos.begin).match.fn === null) {
  2016. pos.begin = seekNext(pos.begin);
  2017. }
  2018. pos.end = seekPrevious(pos.begin, true);
  2019. pos.begin = seekPrevious(pos.end, true);
  2020. } else {
  2021. pos.begin = seekNext(pos.begin, true);
  2022. pos.end = seekNext(pos.begin, true);
  2023. if (pos.end < getMaskSet().maskLength) pos.end--;
  2024. }
  2025. if (pos.begin < getMaskSet().maskLength) {
  2026. e.preventDefault();
  2027. caret(input, pos.begin, pos.end);
  2028. }
  2029. } else if (!e.shiftKey) {
  2030. if (opts.insertMode === false) {
  2031. if (k === Inputmask.keyCode.RIGHT) {
  2032. setTimeout(function () {
  2033. var caretPos = caret(input);
  2034. caret(input, caretPos.begin);
  2035. }, 0);
  2036. } else if (k === Inputmask.keyCode.LEFT) {
  2037. setTimeout(function () {
  2038. var caretPos = caret(input);
  2039. caret(input, isRTL ? caretPos.begin + 1 : caretPos.begin - 1);
  2040. }, 0);
  2041. }
  2042. }
  2043. }
  2044. opts.onKeyDown.call(this, e, getBuffer(), caret(input).begin, opts);
  2045. ignorable = $.inArray(k, opts.ignorables) !== -1;
  2046. },
  2047. keypressEvent: function (e, checkval, writeOut, strict, ndx) {
  2048. var input = this,
  2049. $input = $(input),
  2050. k = e.which || e.charCode || e.keyCode;
  2051. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  2052. if (k === Inputmask.keyCode.ENTER && undoValue !== getBuffer().join("")) {
  2053. undoValue = getBuffer().join("");
  2054. // e.preventDefault();
  2055. setTimeout(function () {
  2056. $input.trigger("change");
  2057. }, 0);
  2058. }
  2059. return true;
  2060. } else {
  2061. if (k) {
  2062. //special treat the decimal separator
  2063. if (k === 46 && e.shiftKey === false && opts.radixPoint === ",") k = 44;
  2064. var pos = checkval ? {
  2065. begin: ndx,
  2066. end: ndx
  2067. } : caret(input),
  2068. forwardPosition, c = String.fromCharCode(k);
  2069. getMaskSet().writeOutBuffer = true;
  2070. var valResult = isValid(pos, c, strict);
  2071. if (valResult !== false) {
  2072. resetMaskSet(true);
  2073. forwardPosition = valResult.caret !== undefined ? valResult.caret : checkval ? valResult.pos + 1 : seekNext(valResult.pos);
  2074. getMaskSet().p = forwardPosition; //needed for checkval
  2075. }
  2076. if (writeOut !== false) {
  2077. var self = this;
  2078. setTimeout(function () {
  2079. opts.onKeyValidation.call(self, k, valResult, opts);
  2080. }, 0);
  2081. if (getMaskSet().writeOutBuffer && valResult !== false) {
  2082. var buffer = getBuffer();
  2083. writeBuffer(input, buffer, (opts.numericInput && valResult.caret === undefined) ? seekPrevious(forwardPosition) : forwardPosition, e, checkval !== true);
  2084. if (checkval !== true) {
  2085. setTimeout(function () { //timeout needed for IE
  2086. if (isComplete(buffer) === true) $input.trigger("complete");
  2087. }, 0);
  2088. }
  2089. }
  2090. }
  2091. e.preventDefault();
  2092. if (checkval) {
  2093. valResult.forwardPosition = forwardPosition;
  2094. return valResult;
  2095. }
  2096. }
  2097. }
  2098. },
  2099. pasteEvent: function (e) {
  2100. var input = this,
  2101. ev = e.originalEvent || e,
  2102. $input = $(input),
  2103. inputValue = input.inputmask._valueGet(true),
  2104. caretPos = caret(input),
  2105. tempValue;
  2106. if (isRTL) {
  2107. tempValue = caretPos.end;
  2108. caretPos.end = caretPos.begin;
  2109. caretPos.begin = tempValue;
  2110. }
  2111. var valueBeforeCaret = inputValue.substr(0, caretPos.begin),
  2112. valueAfterCaret = inputValue.substr(caretPos.end, inputValue.length);
  2113. if (valueBeforeCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(0, caretPos.begin).join("")) valueBeforeCaret = "";
  2114. if (valueAfterCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(caretPos.end).join("")) valueAfterCaret = "";
  2115. if (isRTL) {
  2116. tempValue = valueBeforeCaret;
  2117. valueBeforeCaret = valueAfterCaret;
  2118. valueAfterCaret = tempValue;
  2119. }
  2120. if (window.clipboardData && window.clipboardData.getData) { // IE
  2121. inputValue = valueBeforeCaret + window.clipboardData.getData("Text") + valueAfterCaret;
  2122. } else if (ev.clipboardData && ev.clipboardData.getData) {
  2123. inputValue = valueBeforeCaret + ev.clipboardData.getData("text/plain") + valueAfterCaret;
  2124. } else return true; //allow native paste event as fallback ~ masking will continue by inputfallback
  2125. var pasteValue = inputValue;
  2126. if ($.isFunction(opts.onBeforePaste)) {
  2127. pasteValue = opts.onBeforePaste(inputValue, opts);
  2128. if (pasteValue === false) {
  2129. return e.preventDefault();
  2130. }
  2131. if (!pasteValue) {
  2132. pasteValue = inputValue;
  2133. }
  2134. }
  2135. checkVal(input, false, false, isRTL ? pasteValue.split("").reverse() : pasteValue.toString().split(""));
  2136. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()), e, undoValue !== getBuffer().join(""));
  2137. if (isComplete(getBuffer()) === true) {
  2138. $input.trigger("complete");
  2139. }
  2140. return e.preventDefault();
  2141. },
  2142. inputFallBackEvent: function (e) { //fallback when keypress fails
  2143. var input = this,
  2144. inputValue = input.inputmask._valueGet();
  2145. //console.log(inputValue);
  2146. if (getBuffer().join("") !== inputValue) {
  2147. var caretPos = caret(input);
  2148. inputValue = inputValue.replace(new RegExp("(" + Inputmask.escapeRegex(getBufferTemplate().join("")) + ")*"), "");
  2149. if (iemobile) { //iemobile just set the character at the end althought the caret position is correctly set
  2150. var inputChar = inputValue.replace(getBuffer().join(""), "");
  2151. if (inputChar.length === 1) {
  2152. var keypress = new $.Event("keypress");
  2153. keypress.which = inputChar.charCodeAt(0);
  2154. EventHandlers.keypressEvent.call(input, keypress, true, true, false, getMaskSet().validPositions[caretPos.begin - 1] ? caretPos.begin : caretPos.begin - 1);
  2155. return false;
  2156. }
  2157. }
  2158. if (caretPos.begin > inputValue.length) {
  2159. caret(input, inputValue.length);
  2160. caretPos = caret(input);
  2161. }
  2162. //detect & treat possible backspace before static
  2163. if ((getBuffer().length - inputValue.length) === 1 && inputValue.charAt(caretPos.begin) !== getBuffer()[caretPos.begin] && inputValue.charAt(caretPos.begin + 1) !== getBuffer()[caretPos.begin] && !isMask(caretPos.begin)) {
  2164. e.keyCode = Inputmask.keyCode.BACKSPACE;
  2165. EventHandlers.keydownEvent.call(input, e);
  2166. } else {
  2167. var lvp = getLastValidPosition() + 1;
  2168. var bufferTemplate = getBufferTemplate().join(""); //getBuffer().slice(lvp).join('');
  2169. while (inputValue.match(Inputmask.escapeRegex(bufferTemplate) + "$") === null) {
  2170. bufferTemplate = bufferTemplate.slice(1);
  2171. }
  2172. inputValue = inputValue.replace(bufferTemplate, "");
  2173. inputValue = inputValue.split("");
  2174. checkVal(input, true, false, inputValue, e, caretPos.begin < lvp);
  2175. if (isComplete(getBuffer()) === true) {
  2176. $(input).trigger("complete");
  2177. }
  2178. }
  2179. e.preventDefault();
  2180. }
  2181. },
  2182. setValueEvent: function (e) {
  2183. var input = this,
  2184. value = input.inputmask._valueGet();
  2185. checkVal(input, true, false, ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(value, opts) || value) : value).split(""));
  2186. undoValue = getBuffer().join("");
  2187. if ((opts.clearMaskOnLostFocus || opts.clearIncomplete) && input.inputmask._valueGet() === getBufferTemplate().join("")) {
  2188. input.inputmask._valueSet("");
  2189. }
  2190. },
  2191. focusEvent: function (e) {
  2192. var input = this,
  2193. nptValue = input.inputmask._valueGet();
  2194. if (opts.showMaskOnFocus && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue === ""))) {
  2195. if (input.inputmask._valueGet() !== getBuffer().join("")) {
  2196. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
  2197. } else if (mouseEnter === false) { //only executed on focus without mouseenter
  2198. caret(input, seekNext(getLastValidPosition()));
  2199. }
  2200. }
  2201. if (opts.positionCaretOnTab === true) {
  2202. EventHandlers.clickEvent.apply(input, [e, true]);
  2203. }
  2204. undoValue = getBuffer().join("");
  2205. },
  2206. mouseleaveEvent: function (e) {
  2207. var input = this;
  2208. mouseEnter = false;
  2209. if (opts.clearMaskOnLostFocus && document.activeElement !== input) {
  2210. var buffer = getBuffer().slice(),
  2211. nptValue = input.inputmask._valueGet();
  2212. if (nptValue !== input.getAttribute("placeholder") && nptValue !== "") {
  2213. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  2214. buffer = [];
  2215. } else { //clearout optional tail of the mask
  2216. clearOptionalTail(buffer);
  2217. }
  2218. writeBuffer(input, buffer);
  2219. }
  2220. }
  2221. },
  2222. clickEvent: function (e, tabbed) {
  2223. function doRadixFocus(clickPos) {
  2224. if (opts.radixPoint !== "") {
  2225. var vps = getMaskSet().validPositions;
  2226. if (vps[clickPos] === undefined || (vps[clickPos].input === getPlaceholder(clickPos))) {
  2227. if (clickPos < seekNext(-1)) return true;
  2228. var radixPos = $.inArray(opts.radixPoint, getBuffer());
  2229. if (radixPos !== -1) {
  2230. for (var vp in vps) {
  2231. if (radixPos < vp && vps[vp].input !== getPlaceholder(vp)) {
  2232. return false;
  2233. }
  2234. }
  2235. return true;
  2236. }
  2237. }
  2238. }
  2239. return false;
  2240. }
  2241. var input = this;
  2242. setTimeout(function () { //needed for Chrome ~ initial selection clears after the clickevent
  2243. if (document.activeElement === input) {
  2244. var selectedCaret = caret(input);
  2245. if (tabbed) selectedCaret.begin = selectedCaret.end;
  2246. if (selectedCaret.begin === selectedCaret.end) {
  2247. switch (opts.positionCaretOnClick) {
  2248. case "none":
  2249. break;
  2250. case "radixFocus":
  2251. if (doRadixFocus(selectedCaret.begin)) {
  2252. var radixPos = $.inArray(opts.radixPoint, getBuffer().join(""));
  2253. caret(input, opts.numericInput ? seekNext(radixPos) : radixPos);
  2254. break;
  2255. }
  2256. default: //lvp:
  2257. var clickPosition = selectedCaret.begin,
  2258. lvclickPosition = getLastValidPosition(clickPosition, true),
  2259. lastPosition = seekNext(lvclickPosition);
  2260. if (clickPosition < lastPosition) {
  2261. caret(input, !isMask(clickPosition) && !isMask(clickPosition - 1) ? seekNext(clickPosition) : clickPosition);
  2262. } else {
  2263. var placeholder = getPlaceholder(lastPosition);
  2264. if ((placeholder !== "" && getBuffer()[lastPosition] !== placeholder && getTest(lastPosition).match.optionalQuantifier !== true) || (!isMask(lastPosition) && getTest(lastPosition).match.def === placeholder)) {
  2265. lastPosition = seekNext(lastPosition);
  2266. }
  2267. caret(input, lastPosition);
  2268. }
  2269. break;
  2270. }
  2271. }
  2272. }
  2273. }, 0);
  2274. },
  2275. dblclickEvent: function (e) {
  2276. var input = this;
  2277. setTimeout(function () {
  2278. caret(input, 0, seekNext(getLastValidPosition()));
  2279. }, 0);
  2280. },
  2281. cutEvent: function (e) {
  2282. var input = this,
  2283. $input = $(input),
  2284. pos = caret(input),
  2285. ev = e.originalEvent || e;
  2286. //correct clipboardData
  2287. var clipboardData = window.clipboardData || ev.clipboardData,
  2288. clipData = isRTL ? getBuffer().slice(pos.end, pos.begin) : getBuffer().slice(pos.begin, pos.end);
  2289. clipboardData.setData("text", isRTL ? clipData.reverse().join("") : clipData.join(""));
  2290. if (document.execCommand) document.execCommand("copy"); // copy selected content to system clipbaord
  2291. handleRemove(input, Inputmask.keyCode.DELETE, pos);
  2292. writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join(""));
  2293. if (input.inputmask._valueGet() === getBufferTemplate().join("")) {
  2294. $input.trigger("cleared");
  2295. }
  2296. },
  2297. blurEvent: function (e) {
  2298. var $input = $(this),
  2299. input = this;
  2300. if (input.inputmask) {
  2301. var nptValue = input.inputmask._valueGet(),
  2302. buffer = getBuffer().slice();
  2303. if (undoValue !== buffer.join("")) {
  2304. setTimeout(function () { //change event should be triggered after the other buffer manipulations on blur
  2305. $input.trigger("change");
  2306. undoValue = buffer.join("");
  2307. }, 0);
  2308. }
  2309. if (nptValue !== "") {
  2310. if (opts.clearMaskOnLostFocus) {
  2311. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  2312. buffer = [];
  2313. } else { //clearout optional tail of the mask
  2314. clearOptionalTail(buffer);
  2315. }
  2316. }
  2317. if (isComplete(buffer) === false) {
  2318. setTimeout(function () {
  2319. $input.trigger("incomplete");
  2320. }, 0);
  2321. if (opts.clearIncomplete) {
  2322. resetMaskSet();
  2323. if (opts.clearMaskOnLostFocus) {
  2324. buffer = [];
  2325. } else {
  2326. buffer = getBufferTemplate().slice();
  2327. }
  2328. }
  2329. }
  2330. writeBuffer(input, buffer, undefined, e);
  2331. }
  2332. }
  2333. },
  2334. mouseenterEvent: function (e) {
  2335. var input = this;
  2336. mouseEnter = true;
  2337. if (document.activeElement !== input && opts.showMaskOnHover) {
  2338. if (input.inputmask._valueGet() !== getBuffer().join("")) {
  2339. writeBuffer(input, getBuffer());
  2340. }
  2341. }
  2342. },
  2343. submitEvent: function (e) { //trigger change on submit if any
  2344. if (undoValue !== getBuffer().join("")) {
  2345. $el.trigger("change");
  2346. }
  2347. if (opts.clearMaskOnLostFocus && getLastValidPosition() === -1 && el.inputmask._valueGet && el.inputmask._valueGet() === getBufferTemplate().join("")) {
  2348. el.inputmask._valueSet(""); //clear masktemplete on submit and still has focus
  2349. }
  2350. if (opts.removeMaskOnSubmit) {
  2351. el.inputmask._valueSet(el.inputmask.unmaskedvalue(), true);
  2352. setTimeout(function () {
  2353. writeBuffer(el, getBuffer());
  2354. }, 0);
  2355. }
  2356. },
  2357. resetEvent: function (e) {
  2358. setTimeout(function () {
  2359. $el.trigger("setvalue");
  2360. }, 0);
  2361. }
  2362. };
  2363. function initializeColorMask(input) {
  2364. function findCaretPos(clientx) {
  2365. //calculate text width
  2366. var e = document.createElement('span'), caretPos;
  2367. for (var style in computedStyle) { //clone styles
  2368. if (isNaN(style) && style.indexOf("font") !== -1) {
  2369. e.style[style] = computedStyle[style];
  2370. }
  2371. }
  2372. e.style.textTransform = computedStyle.textTransform;
  2373. e.style.letterSpacing = computedStyle.letterSpacing;
  2374. e.style.position = "absolute";
  2375. e.style.height = "auto";
  2376. e.style.width = "auto";
  2377. e.style.visibility = "hidden";
  2378. e.style.whiteSpace = "nowrap";
  2379. document.body.appendChild(e);
  2380. var inputText = input.inputmask._valueGet(), previousWidth = 0, itl;
  2381. for (caretPos = 0, itl = inputText.length; caretPos <= itl; caretPos++) {
  2382. e.innerHTML += inputText.charAt(caretPos) || "_";
  2383. if (e.offsetWidth >= clientx) {
  2384. var offset1 = (clientx - previousWidth);
  2385. var offset2 = e.offsetWidth - clientx;
  2386. e.innerHTML = inputText.charAt(caretPos);
  2387. offset1 -= (e.offsetWidth / 3);
  2388. caretPos = offset1 < offset2 ? caretPos - 1 : caretPos;
  2389. break;
  2390. }
  2391. previousWidth = e.offsetWidth;
  2392. }
  2393. document.body.removeChild(e);
  2394. return caretPos;
  2395. }
  2396. function position() {
  2397. colorMask.style.position = "absolute";
  2398. colorMask.style.top = offset.top + "px";
  2399. colorMask.style.left = offset.left + "px";
  2400. colorMask.style.width = parseInt(input.offsetWidth) - parseInt(computedStyle.paddingLeft) - parseInt(computedStyle.paddingRight) - parseInt(computedStyle.borderLeftWidth) - parseInt(computedStyle.borderRightWidth) + "px";
  2401. colorMask.style.height = parseInt(input.offsetHeight) - parseInt(computedStyle.paddingTop) - parseInt(computedStyle.paddingBottom) - parseInt(computedStyle.borderTopWidth) - parseInt(computedStyle.borderBottomWidth) + "px";
  2402. colorMask.style.lineHeight = colorMask.style.height;
  2403. colorMask.style.zIndex = isNaN(computedStyle.zIndex) ? -1 : computedStyle.zIndex - 1;
  2404. colorMask.style.webkitAppearance = "textfield";
  2405. colorMask.style.mozAppearance = "textfield";
  2406. colorMask.style.Appearance = "textfield";
  2407. }
  2408. var offset = $(input).position(),
  2409. computedStyle = (input.ownerDocument.defaultView || window).getComputedStyle(input, null),
  2410. parentNode = input.parentNode;
  2411. colorMask = document.createElement("div");
  2412. document.body.appendChild(colorMask); //insert at body to prevent css clash :last-child for example
  2413. for (var style in computedStyle) { //clone styles
  2414. if (isNaN(style) && style !== "cssText" && style.indexOf("webkit") == -1) {
  2415. colorMask.style[style] = computedStyle[style];
  2416. }
  2417. }
  2418. //restyle input
  2419. input.style.backgroundColor = "transparent";
  2420. input.style.color = "transparent";
  2421. input.style.webkitAppearance = "caret";
  2422. input.style.mozAppearance = "caret";
  2423. input.style.Appearance = "caret";
  2424. position();
  2425. //event passthrough
  2426. $(window).on("resize", function (e) {
  2427. offset = $(input).position();
  2428. computedStyle = (input.ownerDocument.defaultView || window).getComputedStyle(input, null);
  2429. position();
  2430. });
  2431. $(input).on("click", function (e) {
  2432. caret(input, findCaretPos(e.clientX));
  2433. return EventHandlers.clickEvent.call(this, [e]);
  2434. });
  2435. $(input).on("keydown", function (e) {
  2436. if (!e.shiftKey && opts.insertMode !== false) {
  2437. setTimeout(function () {
  2438. renderColorMask(input);
  2439. }, 0);
  2440. }
  2441. });
  2442. }
  2443. function renderColorMask(input, buffer, caretPos) {
  2444. function handleStatic() {
  2445. if (!isStatic && (test.fn === null || testPos.input === undefined)) {
  2446. isStatic = true;
  2447. maskTemplate += "<span class='im-static''>"
  2448. } else if (isStatic && (test.fn !== null && testPos.input !== undefined)) {
  2449. isStatic = false;
  2450. maskTemplate += "</span>"
  2451. }
  2452. }
  2453. if (colorMask !== undefined) {
  2454. buffer = buffer || getBuffer();
  2455. if (caretPos === undefined) {
  2456. caretPos = caret(input);
  2457. } else if (caretPos.begin === undefined) {
  2458. caretPos = {begin: caretPos, end: caretPos};
  2459. }
  2460. var maskTemplate = "", isStatic = false;
  2461. if (buffer != "") {
  2462. var ndxIntlzr, pos = 0,
  2463. test, testPos, lvp = getLastValidPosition();
  2464. do {
  2465. if (pos === caretPos.begin && document.activeElement === input) {
  2466. maskTemplate += "<span class='im-caret' style='border-right-width: 1px;border-right-style: solid;'></span>";
  2467. }
  2468. if (getMaskSet().validPositions[pos]) {
  2469. testPos = getMaskSet().validPositions[pos];
  2470. test = testPos.match;
  2471. ndxIntlzr = testPos.locator.slice();
  2472. handleStatic();
  2473. maskTemplate += testPos.input;
  2474. } else {
  2475. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  2476. test = testPos.match;
  2477. ndxIntlzr = testPos.locator.slice();
  2478. if (opts.jitMasking === false || pos < lvp || (typeof opts.jitMasking === "number" && isFinite(opts.jitMasking) && opts.jitMasking > pos)) {
  2479. handleStatic();
  2480. maskTemplate += getPlaceholder(pos, test);
  2481. }
  2482. }
  2483. pos++;
  2484. } while ((maxLength === undefined || pos < maxLength) && (test.fn !== null || test.def !== "") || lvp > pos);
  2485. }
  2486. colorMask.innerHTML = maskTemplate;
  2487. }
  2488. }
  2489. function mask(elem) {
  2490. function isElementTypeSupported(input, opts) {
  2491. function patchValueProperty(npt) {
  2492. var valueGet;
  2493. var valueSet;
  2494. function patchValhook(type) {
  2495. if ($.valHooks && ($.valHooks[type] === undefined || $.valHooks[type].inputmaskpatch !== true)) {
  2496. var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) {
  2497. return elem.value;
  2498. };
  2499. var valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
  2500. elem.value = value;
  2501. return elem;
  2502. };
  2503. $.valHooks[type] = {
  2504. get: function (elem) {
  2505. if (elem.inputmask) {
  2506. if (elem.inputmask.opts.autoUnmask) {
  2507. return elem.inputmask.unmaskedvalue();
  2508. } else {
  2509. var result = valhookGet(elem);
  2510. return getLastValidPosition(undefined, undefined, elem.inputmask.maskset.validPositions) !== -1 || opts.nullable !== true ? result : "";
  2511. }
  2512. } else return valhookGet(elem);
  2513. },
  2514. set: function (elem, value) {
  2515. var $elem = $(elem),
  2516. result;
  2517. result = valhookSet(elem, value);
  2518. if (elem.inputmask) {
  2519. $elem.trigger("setvalue");
  2520. }
  2521. return result;
  2522. },
  2523. inputmaskpatch: true
  2524. };
  2525. }
  2526. }
  2527. function getter() {
  2528. if (this.inputmask) {
  2529. return this.inputmask.opts.autoUnmask ?
  2530. this.inputmask.unmaskedvalue() :
  2531. (getLastValidPosition() !== -1 || opts.nullable !== true ?
  2532. (document.activeElement === this && opts.clearMaskOnLostFocus ?
  2533. (isRTL ? clearOptionalTail(getBuffer().slice()).reverse() : clearOptionalTail(getBuffer().slice())).join("") :
  2534. valueGet.call(this)) :
  2535. "");
  2536. } else return valueGet.call(this);
  2537. }
  2538. function setter(value) {
  2539. valueSet.call(this, value);
  2540. if (this.inputmask) {
  2541. $(this).trigger("setvalue");
  2542. }
  2543. }
  2544. function installNativeValueSetFallback(npt) {
  2545. EventRuler.on(npt, "mouseenter", function (event) {
  2546. var $input = $(this),
  2547. input = this,
  2548. value = input.inputmask._valueGet();
  2549. if (value !== getBuffer().join("") /*&& getLastValidPosition() > 0*/) {
  2550. $input.trigger("setvalue");
  2551. }
  2552. });
  2553. }
  2554. if (!npt.inputmask.__valueGet) {
  2555. if (opts.noValuePatching !== true) {
  2556. if (Object.getOwnPropertyDescriptor) {
  2557. if (typeof Object.getPrototypeOf !== "function") {
  2558. Object.getPrototypeOf = typeof "test".__proto__ === "object" ? function (object) {
  2559. return object.__proto__;
  2560. } : function (object) {
  2561. return object.constructor.prototype;
  2562. };
  2563. }
  2564. var valueProperty = Object.getPrototypeOf ? Object.getOwnPropertyDescriptor(Object.getPrototypeOf(npt), "value") : undefined;
  2565. if (valueProperty && valueProperty.get && valueProperty.set) {
  2566. valueGet = valueProperty.get;
  2567. valueSet = valueProperty.set;
  2568. Object.defineProperty(npt, "value", {
  2569. get: getter,
  2570. set: setter,
  2571. configurable: true
  2572. });
  2573. } else if (npt.tagName !== "INPUT") {
  2574. valueGet = function () {
  2575. return this.textContent;
  2576. };
  2577. valueSet = function (value) {
  2578. this.textContent = value;
  2579. };
  2580. Object.defineProperty(npt, "value", {
  2581. get: getter,
  2582. set: setter,
  2583. configurable: true
  2584. });
  2585. }
  2586. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  2587. valueGet = npt.__lookupGetter__("value");
  2588. valueSet = npt.__lookupSetter__("value");
  2589. npt.__defineGetter__("value", getter);
  2590. npt.__defineSetter__("value", setter);
  2591. }
  2592. npt.inputmask.__valueGet = valueGet; //store native property getter
  2593. npt.inputmask.__valueSet = valueSet; //store native property setter
  2594. }
  2595. npt.inputmask._valueGet = function (overruleRTL) {
  2596. return isRTL && overruleRTL !== true ? valueGet.call(this.el).split("").reverse().join("") : valueGet.call(this.el);
  2597. };
  2598. npt.inputmask._valueSet = function (value, overruleRTL) { //null check is needed for IE8 => otherwise converts to "null"
  2599. valueSet.call(this.el, (value === null || value === undefined) ? "" : ((overruleRTL !== true && isRTL) ? value.split("").reverse().join("") : value));
  2600. };
  2601. if (valueGet === undefined) { //jquery.val fallback
  2602. valueGet = function () {
  2603. return this.value;
  2604. };
  2605. valueSet = function (value) {
  2606. this.value = value;
  2607. };
  2608. patchValhook(npt.type);
  2609. installNativeValueSetFallback(npt);
  2610. }
  2611. }
  2612. }
  2613. var elementType = input.getAttribute("type");
  2614. var isSupported = (input.tagName === "INPUT" && $.inArray(elementType, opts.supportsInputType) !== -1) || input.isContentEditable || input.tagName === "TEXTAREA";
  2615. if (!isSupported) {
  2616. if (input.tagName === "INPUT") {
  2617. var el = document.createElement("input");
  2618. el.setAttribute("type", elementType);
  2619. isSupported = el.type === "text"; //apply mask only if the type is not natively supported
  2620. el = null;
  2621. } else isSupported = "partial";
  2622. }
  2623. if (isSupported !== false) {
  2624. patchValueProperty(input);
  2625. }
  2626. return isSupported;
  2627. }
  2628. var isSupported = isElementTypeSupported(elem, opts);
  2629. if (isSupported !== false) {
  2630. el = elem;
  2631. $el = $(el);
  2632. if (el.dir === "rtl" || opts.rightAlign) {
  2633. el.style.textAlign = "right";
  2634. }
  2635. if (el.dir === "rtl" || opts.numericInput) {
  2636. el.dir = "ltr";
  2637. el.removeAttribute("dir");
  2638. el.inputmask.isRTL = true;
  2639. isRTL = true;
  2640. }
  2641. if (opts.colorMask === true) {
  2642. initializeColorMask(el);
  2643. }
  2644. if (android) {
  2645. if (el.hasOwnProperty("inputmode")) {
  2646. el.inputmode = opts.inputmode;
  2647. el.setAttribute("inputmode", opts.inputmode);
  2648. }
  2649. if (opts.androidHack === "rtfm") {
  2650. if (opts.colorMask !== true) {
  2651. initializeColorMask(el);
  2652. }
  2653. el.type = "password";
  2654. }
  2655. }
  2656. //unbind all events - to make sure that no other mask will interfere when re-masking
  2657. EventRuler.off(el);
  2658. if (isSupported === true) {
  2659. //bind events
  2660. EventRuler.on(el, "submit", EventHandlers.submitEvent);
  2661. EventRuler.on(el, "reset", EventHandlers.resetEvent);
  2662. EventRuler.on(el, "mouseenter", EventHandlers.mouseenterEvent);
  2663. EventRuler.on(el, "blur", EventHandlers.blurEvent);
  2664. EventRuler.on(el, "focus", EventHandlers.focusEvent);
  2665. EventRuler.on(el, "mouseleave", EventHandlers.mouseleaveEvent);
  2666. if (opts.colorMask !== true)
  2667. EventRuler.on(el, "click", EventHandlers.clickEvent);
  2668. EventRuler.on(el, "dblclick", EventHandlers.dblclickEvent);
  2669. EventRuler.on(el, "paste", EventHandlers.pasteEvent);
  2670. EventRuler.on(el, "dragdrop", EventHandlers.pasteEvent);
  2671. EventRuler.on(el, "drop", EventHandlers.pasteEvent);
  2672. EventRuler.on(el, "cut", EventHandlers.cutEvent);
  2673. EventRuler.on(el, "complete", opts.oncomplete);
  2674. EventRuler.on(el, "incomplete", opts.onincomplete);
  2675. EventRuler.on(el, "cleared", opts.oncleared);
  2676. if (opts.inputEventOnly !== true) {
  2677. EventRuler.on(el, "keydown", EventHandlers.keydownEvent);
  2678. EventRuler.on(el, "keypress", EventHandlers.keypressEvent);
  2679. }
  2680. EventRuler.on(el, "compositionstart", $.noop);
  2681. EventRuler.on(el, "compositionupdate", $.noop);
  2682. EventRuler.on(el, "compositionend", $.noop);
  2683. EventRuler.on(el, "keyup", $.noop);
  2684. EventRuler.on(el, "input", EventHandlers.inputFallBackEvent);
  2685. }
  2686. EventRuler.on(el, "setvalue", EventHandlers.setValueEvent);
  2687. //apply mask
  2688. getBufferTemplate(); //initialize the buffer and getmasklength
  2689. if (el.inputmask._valueGet() !== "" || opts.clearMaskOnLostFocus === false || document.activeElement === el) {
  2690. var initialValue = $.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(el.inputmask._valueGet(), opts) || el.inputmask._valueGet()) : el.inputmask._valueGet();
  2691. checkVal(el, true, false, initialValue.split(""));
  2692. var buffer = getBuffer().slice();
  2693. undoValue = buffer.join("");
  2694. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  2695. if (isComplete(buffer) === false) {
  2696. if (opts.clearIncomplete) {
  2697. resetMaskSet();
  2698. }
  2699. }
  2700. if (opts.clearMaskOnLostFocus && document.activeElement !== el) {
  2701. if (getLastValidPosition() === -1) {
  2702. buffer = [];
  2703. } else {
  2704. clearOptionalTail(buffer);
  2705. }
  2706. }
  2707. writeBuffer(el, buffer);
  2708. if (document.activeElement === el) { //position the caret when in focus
  2709. caret(el, seekNext(getLastValidPosition()));
  2710. }
  2711. }
  2712. }
  2713. }
  2714. //action object
  2715. var valueBuffer;
  2716. if (actionObj !== undefined) {
  2717. switch (actionObj.action) {
  2718. case "isComplete":
  2719. el = actionObj.el;
  2720. return isComplete(getBuffer());
  2721. case "unmaskedvalue":
  2722. if (el === undefined || actionObj.value !== undefined) {
  2723. valueBuffer = actionObj.value;
  2724. valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(valueBuffer, opts) || valueBuffer) : valueBuffer).split("");
  2725. checkVal(undefined, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  2726. if ($.isFunction(opts.onBeforeWrite)) opts.onBeforeWrite(undefined, getBuffer(), 0, opts);
  2727. }
  2728. return unmaskedvalue(el);
  2729. case "mask":
  2730. mask(el);
  2731. break;
  2732. case "format":
  2733. valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(actionObj.value, opts) || actionObj.value) : actionObj.value).split("");
  2734. checkVal(undefined, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  2735. if ($.isFunction(opts.onBeforeWrite)) opts.onBeforeWrite(undefined, getBuffer(), 0, opts);
  2736. if (actionObj.metadata) {
  2737. return {
  2738. value: isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join(""),
  2739. metadata: maskScope.call(this, {
  2740. "action": "getmetadata"
  2741. }, maskset, opts)
  2742. };
  2743. }
  2744. return isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join("");
  2745. case "isValid":
  2746. if (actionObj.value) {
  2747. valueBuffer = actionObj.value.split("");
  2748. checkVal(undefined, false, true, isRTL ? valueBuffer.reverse() : valueBuffer);
  2749. } else {
  2750. actionObj.value = getBuffer().join("");
  2751. }
  2752. var buffer = getBuffer();
  2753. var rl = determineLastRequiredPosition(),
  2754. lmib = buffer.length - 1;
  2755. for (; lmib > rl; lmib--) {
  2756. if (isMask(lmib)) break;
  2757. }
  2758. buffer.splice(rl, lmib + 1 - rl);
  2759. return isComplete(buffer) && actionObj.value === getBuffer().join("");
  2760. case "getemptymask":
  2761. return getBufferTemplate().join("");
  2762. case "remove":
  2763. if (el) {
  2764. $el = $(el);
  2765. //writeout the unmaskedvalue
  2766. el.inputmask._valueSet(unmaskedvalue(el));
  2767. //unbind all events
  2768. EventRuler.off(el);
  2769. //restore the value property
  2770. var valueProperty;
  2771. if (Object.getOwnPropertyDescriptor && Object.getPrototypeOf) {
  2772. valueProperty = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el), "value");
  2773. if (valueProperty) {
  2774. if (el.inputmask.__valueGet) {
  2775. Object.defineProperty(el, "value", {
  2776. get: el.inputmask.__valueGet,
  2777. set: el.inputmask.__valueSet,
  2778. configurable: true
  2779. });
  2780. }
  2781. }
  2782. } else if (document.__lookupGetter__ && el.__lookupGetter__("value")) {
  2783. if (el.inputmask.__valueGet) {
  2784. el.__defineGetter__("value", el.inputmask.__valueGet);
  2785. el.__defineSetter__("value", el.inputmask.__valueSet);
  2786. }
  2787. }
  2788. //clear data
  2789. el.inputmask = undefined;
  2790. }
  2791. return el;
  2792. break;
  2793. case "getmetadata":
  2794. if ($.isArray(maskset.metadata)) {
  2795. var maskTarget = getMaskTemplate(true, 0, false).join("");
  2796. $.each(maskset.metadata, function (ndx, mtdt) {
  2797. if (mtdt.mask === maskTarget) {
  2798. maskTarget = mtdt;
  2799. return false;
  2800. }
  2801. });
  2802. return maskTarget;
  2803. }
  2804. return maskset.metadata;
  2805. }
  2806. }
  2807. }
  2808. //make inputmask available
  2809. window.Inputmask = Inputmask;
  2810. return Inputmask;
  2811. }));