inputmask.js 115 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033
  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. this.refreshValue = false, //indicate a refresh from the inputvalue is needed (form.reset)
  44. resolveAlias(this.opts.alias, options, this.opts);
  45. }
  46. Inputmask.prototype = {
  47. //options default
  48. defaults: {
  49. placeholder: "_",
  50. optionalmarker: {
  51. start: "[",
  52. end: "]"
  53. },
  54. quantifiermarker: {
  55. start: "{",
  56. end: "}"
  57. },
  58. groupmarker: {
  59. start: "(",
  60. end: ")"
  61. },
  62. alternatormarker: "|",
  63. escapeChar: "\\",
  64. mask: null, //needs tobe null instead of undefined as the extend method does not consider props with the undefined value
  65. oncomplete: $.noop, //executes when the mask is complete
  66. onincomplete: $.noop, //executes when the mask is incomplete and focus is lost
  67. oncleared: $.noop, //executes when the mask is cleared
  68. repeat: 0, //repetitions of the mask: * ~ forever, otherwise specify an integer
  69. greedy: true, //true: allocated buffer for the mask and repetitions - false: allocate only if needed
  70. autoUnmask: false, //automatically unmask when retrieving the value with $.fn.val or value if the browser supports __lookupGetter__ or getOwnPropertyDescriptor
  71. removeMaskOnSubmit: false, //remove the mask before submitting the form.
  72. clearMaskOnLostFocus: true,
  73. insertMode: true, //insert the input or overwrite the input
  74. clearIncomplete: false, //clear the incomplete input on blur
  75. aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js
  76. alias: null,
  77. onKeyDown: $.noop, //callback to implement autocomplete on certain keys for example. args => event, buffer, caretPos, opts
  78. onBeforeMask: null, //executes before masking the initial value to allow preprocessing of the initial value. args => initialValue, opts => return processedValue
  79. onBeforePaste: function (pastedValue, opts) {
  80. return $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask(pastedValue, opts) : pastedValue;
  81. }, //executes before masking the pasted value to allow preprocessing of the pasted value. args => pastedValue, opts => return processedValue
  82. onBeforeWrite: null, //executes before writing to the masked element. args => event, opts
  83. onUnMask: null, //executes after unmasking to allow postprocessing of the unmaskedvalue. args => maskedValue, unmaskedValue, opts
  84. showMaskOnFocus: true, //show the mask-placeholder when the input has focus
  85. showMaskOnHover: true, //show the mask-placeholder when hovering the empty input
  86. onKeyValidation: $.noop, //executes on every key-press with the result of isValid. Params: key, result, opts
  87. skipOptionalPartCharacter: " ", //a character which can be used to skip an optional part of a mask
  88. numericInput: false, //numericInput input direction style (input shifts to the left while holding the caret position)
  89. rightAlign: false, //align to the right
  90. undoOnEscape: true, //pressing escape reverts the value to the value before focus
  91. //numeric basic properties
  92. radixPoint: "", //".", // | ","
  93. radixPointDefinitionSymbol: undefined, //set the radixPoint definitionSymbol ~ used for awareness of the radixpoint
  94. groupSeparator: "", //",", // | "."
  95. //numeric basic properties
  96. 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
  97. positionCaretOnTab: true, //when enabled the caret position is set after the latest valid position on TAB
  98. tabThrough: false, //allows for tabbing through the different parts of the masked field
  99. supportsInputType: ["text", "tel", "password"], //list with the supported input types
  100. definitions: {
  101. "9": {
  102. validator: "[0-9]",
  103. cardinality: 1,
  104. definitionSymbol: "*"
  105. },
  106. "a": {
  107. validator: "[A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]",
  108. cardinality: 1,
  109. definitionSymbol: "*"
  110. },
  111. "*": {
  112. validator: "[0-9A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]",
  113. cardinality: 1
  114. }
  115. },
  116. //specify keyCodes which should not be considered in the keypress event, otherwise the preventDefault will stop their default behavior especially in FF
  117. 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],
  118. isComplete: null, //override for isComplete - args => buffer, opts - return true || false
  119. canClearPosition: $.noop, //hook to alter the clear behavior in the stripValidPositions args => maskset, position, lastValidPosition, opts => return true|false
  120. postValidation: null, //hook to postValidate the result from isValid. Usefull for validating the entry as a whole. args => buffer, currentResult, opts => return true/false
  121. staticDefinitionSymbol: undefined, //specify a definitionSymbol for static content, used to make matches for alternators
  122. jitMasking: false, //just in time masking ~ only mask while typing, can n (number), true or false
  123. nullable: true, //return nothing instead of the buffertemplate when the user hasn't entered anything.
  124. inputEventOnly: false, //dev option - testing inputfallback behavior
  125. noValuePatching: false, //dev option - disable value property patching
  126. positionCaretOnClick: "lvp", //none, lvp (based on the last valid position (default), radixFocus (position caret to radixpoint on initial click)
  127. casing: null, //mask-level casing. Options: null, "upper", "lower" or "title"
  128. inputmode: "verbatim", //specify the inputmode - already in place for when browsers will support it
  129. colorMask: false, //enable css styleable mask
  130. androidHack: false //see README_android.md
  131. },
  132. masksCache: {},
  133. mask: function (elems) {
  134. var that = this;
  135. function importAttributeOptions(npt, opts, userOptions, dataAttribute) {
  136. var attrOptions = npt.getAttribute(dataAttribute),
  137. option, dataoptions, optionData, p;
  138. function importOption(option, optionData) {
  139. optionData = optionData !== undefined ? optionData : npt.getAttribute(dataAttribute + "-" + option);
  140. if (optionData !== null) {
  141. if (typeof optionData === "string") {
  142. if (option.indexOf("on") === 0) optionData = window[optionData]; //get function definition
  143. else if (optionData === "false") optionData = false;
  144. else if (optionData === "true") optionData = true;
  145. }
  146. userOptions[option] = optionData;
  147. }
  148. }
  149. if (attrOptions && attrOptions !== "") {
  150. attrOptions = attrOptions.replace(new RegExp("'", "g"), '"');
  151. dataoptions = JSON.parse("{" + attrOptions + "}");
  152. }
  153. //resolve aliases
  154. if (dataoptions) { //pickup alias from dataAttribute
  155. optionData = undefined;
  156. for (p in dataoptions) {
  157. if (p.toLowerCase() === "alias") {
  158. optionData = dataoptions[p];
  159. break;
  160. }
  161. }
  162. }
  163. importOption("alias", optionData); //pickup alias from dataAttribute-alias
  164. if (userOptions.alias) {
  165. resolveAlias(userOptions.alias, userOptions, opts);
  166. }
  167. for (option in opts) {
  168. if (dataoptions) {
  169. optionData = undefined;
  170. for (p in dataoptions) {
  171. if (p.toLowerCase() === option.toLowerCase()) {
  172. optionData = dataoptions[p];
  173. break;
  174. }
  175. }
  176. }
  177. importOption(option, optionData);
  178. }
  179. $.extend(true, opts, userOptions);
  180. return opts;
  181. }
  182. if (typeof elems === "string") {
  183. elems = document.getElementById(elems) || document.querySelectorAll(elems);
  184. }
  185. elems = elems.nodeName ? [elems] : elems;
  186. $.each(elems, function (ndx, el) {
  187. var scopedOpts = $.extend(true, {}, that.opts);
  188. importAttributeOptions(el, scopedOpts, $.extend(true, {}, that.userOptions), that.dataAttribute);
  189. var maskset = generateMaskSet(scopedOpts, that.noMasksCache);
  190. if (maskset !== undefined) {
  191. if (el.inputmask !== undefined) {
  192. el.inputmask.remove();
  193. }
  194. //store inputmask instance on the input with element reference
  195. el.inputmask = new Inputmask();
  196. el.inputmask.opts = scopedOpts;
  197. el.inputmask.noMasksCache = that.noMasksCache;
  198. el.inputmask.userOptions = $.extend(true, {}, that.userOptions);
  199. el.inputmask.el = el;
  200. el.inputmask.maskset = maskset;
  201. $.data(el, "_inputmask_opts", scopedOpts);
  202. maskScope.call(el.inputmask, {
  203. "action": "mask"
  204. });
  205. }
  206. });
  207. return elems && elems[0] ? (elems[0].inputmask || this) : this;
  208. },
  209. option: function (options, noremask) { //set extra options || retrieve value of a current option
  210. if (typeof options === "string") {
  211. return this.opts[options];
  212. } else if (typeof options === "object") {
  213. $.extend(this.userOptions, options); //user passed options
  214. //remask
  215. if (this.el && noremask !== true) {
  216. this.mask(this.el);
  217. }
  218. return this;
  219. }
  220. },
  221. unmaskedvalue: function (value) {
  222. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  223. return maskScope.call(this, {
  224. "action": "unmaskedvalue",
  225. "value": value
  226. });
  227. },
  228. remove: function () {
  229. return maskScope.call(this, {
  230. "action": "remove"
  231. });
  232. },
  233. getemptymask: function () { //return the default (empty) mask value, usefull for setting the default value in validation
  234. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  235. return maskScope.call(this, {
  236. "action": "getemptymask"
  237. });
  238. },
  239. hasMaskedValue: function () { //check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value
  240. return !this.opts.autoUnmask;
  241. },
  242. isComplete: function () {
  243. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  244. return maskScope.call(this, {
  245. "action": "isComplete"
  246. });
  247. },
  248. getmetadata: function () { //return mask metadata if exists
  249. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  250. return maskScope.call(this, {
  251. "action": "getmetadata"
  252. });
  253. },
  254. isValid: function (value) {
  255. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  256. return maskScope.call(this, {
  257. "action": "isValid",
  258. "value": value
  259. });
  260. },
  261. format: function (value, metadata) {
  262. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  263. return maskScope.call(this, {
  264. "action": "format",
  265. "value": value,
  266. "metadata": metadata //true/false getmetadata
  267. });
  268. },
  269. analyseMask: function (mask, opts) {
  270. var tokenizer = /(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?\})|[^.?*+^${[]()|\\]+|./g,
  271. escaped = false,
  272. currentToken = new MaskToken(),
  273. match,
  274. m,
  275. openenings = [],
  276. maskTokens = [],
  277. openingToken,
  278. currentOpeningToken,
  279. alternator,
  280. lastMatch,
  281. groupToken;
  282. function MaskToken(isGroup, isOptional, isQuantifier, isAlternator) {
  283. this.matches = [];
  284. this.openGroup = isGroup || false;
  285. this.isGroup = isGroup || false;
  286. this.isOptional = isOptional || false;
  287. this.isQuantifier = isQuantifier || false;
  288. this.isAlternator = isAlternator || false;
  289. this.quantifier = {
  290. min: 1,
  291. max: 1
  292. };
  293. }
  294. //test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, casing: null/upper/lower, def: definitionSymbol, placeholder: placeholder, mask: real maskDefinition}
  295. function insertTestDefinition(mtoken, element, position) {
  296. var maskdef = opts.definitions[element];
  297. position = position !== undefined ? position : mtoken.matches.length;
  298. var prevMatch = mtoken.matches[position - 1];
  299. if (maskdef && !escaped) {
  300. maskdef.placeholder = $.isFunction(maskdef.placeholder) ? maskdef.placeholder(opts) : maskdef.placeholder;
  301. var prevalidators = maskdef.prevalidator,
  302. prevalidatorsL = prevalidators ? prevalidators.length : 0;
  303. //handle prevalidators
  304. for (var i = 1; i < maskdef.cardinality; i++) {
  305. var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [],
  306. validator = prevalidator.validator,
  307. cardinality = prevalidator.cardinality;
  308. mtoken.matches.splice(position++, 0, {
  309. fn: validator ? typeof validator === "string" ? new RegExp(validator) : new function () {
  310. this.test = validator;
  311. } : new RegExp("."),
  312. cardinality: cardinality ? cardinality : 1,
  313. optionality: mtoken.isOptional,
  314. newBlockMarker: prevMatch === undefined || prevMatch.def !== (maskdef.definitionSymbol || element),
  315. casing: maskdef.casing,
  316. def: maskdef.definitionSymbol || element,
  317. placeholder: maskdef.placeholder,
  318. nativeDef: element
  319. });
  320. prevMatch = mtoken.matches[position - 1];
  321. }
  322. mtoken.matches.splice(position++, 0, {
  323. fn: maskdef.validator ? typeof maskdef.validator == "string" ? new RegExp(maskdef.validator) : new function () {
  324. this.test = maskdef.validator;
  325. } : new RegExp("."),
  326. cardinality: maskdef.cardinality,
  327. optionality: mtoken.isOptional,
  328. newBlockMarker: prevMatch === undefined || prevMatch.def !== (maskdef.definitionSymbol || element),
  329. casing: maskdef.casing,
  330. def: maskdef.definitionSymbol || element,
  331. placeholder: maskdef.placeholder,
  332. nativeDef: element
  333. });
  334. } else {
  335. mtoken.matches.splice(position++, 0, {
  336. fn: null,
  337. cardinality: 0,
  338. optionality: mtoken.isOptional,
  339. newBlockMarker: prevMatch === undefined || prevMatch.def !== element,
  340. casing: null,
  341. def: opts.staticDefinitionSymbol || element,
  342. placeholder: opts.staticDefinitionSymbol !== undefined ? element : undefined,
  343. nativeDef: element
  344. });
  345. escaped = false;
  346. }
  347. }
  348. function verifyGroupMarker(maskToken) {
  349. if (maskToken && maskToken.matches) {
  350. $.each(maskToken.matches, function (ndx, token) {
  351. var nextToken = maskToken.matches[ndx + 1];
  352. if ((nextToken === undefined || (nextToken.matches === undefined || nextToken.isQuantifier === false)) && token && token.isGroup) { //this is not a group but a normal mask => convert
  353. token.isGroup = false;
  354. insertTestDefinition(token, opts.groupmarker.start, 0);
  355. if (token.openGroup !== true) {
  356. insertTestDefinition(token, opts.groupmarker.end);
  357. }
  358. }
  359. verifyGroupMarker(token);
  360. }
  361. );
  362. }
  363. }
  364. function defaultCase() {
  365. if (openenings.length > 0) {
  366. currentOpeningToken = openenings[openenings.length - 1];
  367. insertTestDefinition(currentOpeningToken, m);
  368. if (currentOpeningToken.isAlternator) { //handle alternator a | b case
  369. alternator = openenings.pop();
  370. for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
  371. alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group
  372. }
  373. if (openenings.length > 0) {
  374. currentOpeningToken = openenings[openenings.length - 1];
  375. currentOpeningToken.matches.push(alternator);
  376. } else {
  377. currentToken.matches.push(alternator);
  378. }
  379. }
  380. } else {
  381. insertTestDefinition(currentToken, m);
  382. }
  383. }
  384. function reverseTokens(maskToken) {
  385. function reverseStatic(st) {
  386. if (st === opts.optionalmarker.start) st = opts.optionalmarker.end;
  387. else if (st === opts.optionalmarker.end) st = opts.optionalmarker.start;
  388. else if (st === opts.groupmarker.start) st = opts.groupmarker.end;
  389. else if (st === opts.groupmarker.end) st = opts.groupmarker.start;
  390. return st;
  391. }
  392. maskToken.matches = maskToken.matches.reverse();
  393. for (var match in maskToken.matches) {
  394. var intMatch = parseInt(match);
  395. if (maskToken.matches[match].isQuantifier && maskToken.matches[intMatch + 1] && maskToken.matches[intMatch + 1].isGroup) { //reposition quantifier
  396. var qt = maskToken.matches[match];
  397. maskToken.matches.splice(match, 1);
  398. maskToken.matches.splice(intMatch + 1, 0, qt);
  399. }
  400. if (maskToken.matches[match].matches !== undefined) {
  401. maskToken.matches[match] = reverseTokens(maskToken.matches[match]);
  402. } else {
  403. maskToken.matches[match] = reverseStatic(maskToken.matches[match]);
  404. }
  405. }
  406. return maskToken;
  407. }
  408. while (match = tokenizer.exec(mask)) {
  409. m = match[0];
  410. if (escaped) {
  411. defaultCase();
  412. continue;
  413. }
  414. switch (m.charAt(0)) {
  415. case opts.escapeChar:
  416. escaped = true;
  417. break;
  418. case opts.optionalmarker.end:
  419. // optional closing
  420. case opts.groupmarker.end:
  421. // Group closing
  422. openingToken = openenings.pop();
  423. openingToken.openGroup = false; //mark group as complete
  424. if (openingToken !== undefined) {
  425. if (openenings.length > 0) {
  426. currentOpeningToken = openenings[openenings.length - 1];
  427. currentOpeningToken.matches.push(openingToken);
  428. if (currentOpeningToken.isAlternator) { //handle alternator (a) | (b) case
  429. alternator = openenings.pop();
  430. for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
  431. alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group
  432. }
  433. if (openenings.length > 0) {
  434. currentOpeningToken = openenings[openenings.length - 1];
  435. currentOpeningToken.matches.push(alternator);
  436. } else {
  437. currentToken.matches.push(alternator);
  438. }
  439. }
  440. } else {
  441. currentToken.matches.push(openingToken);
  442. }
  443. } else defaultCase();
  444. break;
  445. case opts.optionalmarker.start:
  446. // optional opening
  447. openenings.push(new MaskToken(false, true));
  448. break;
  449. case opts.groupmarker.start:
  450. // Group opening
  451. openenings.push(new MaskToken(true));
  452. break;
  453. case opts.quantifiermarker.start:
  454. //Quantifier
  455. var quantifier = new MaskToken(false, false, true);
  456. m = m.replace(/[{}]/g, "");
  457. var mq = m.split(","),
  458. mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]),
  459. mq1 = mq.length === 1 ? mq0 : (isNaN(mq[1]) ? mq[1] : parseInt(mq[1]));
  460. if (mq1 === "*" || mq1 === "+") {
  461. mq0 = mq1 === "*" ? 0 : 1;
  462. }
  463. quantifier.quantifier = {
  464. min: mq0,
  465. max: mq1
  466. };
  467. if (openenings.length > 0) {
  468. var matches = openenings[openenings.length - 1].matches;
  469. match = matches.pop();
  470. if (!match.isGroup) {
  471. groupToken = new MaskToken(true);
  472. groupToken.matches.push(match);
  473. match = groupToken;
  474. }
  475. matches.push(match);
  476. matches.push(quantifier);
  477. } else {
  478. match = currentToken.matches.pop();
  479. if (!match.isGroup) {
  480. groupToken = new MaskToken(true);
  481. groupToken.matches.push(match);
  482. match = groupToken;
  483. }
  484. currentToken.matches.push(match);
  485. currentToken.matches.push(quantifier);
  486. }
  487. break;
  488. case
  489. opts.alternatormarker:
  490. if (openenings.length > 0) {
  491. currentOpeningToken = openenings[openenings.length - 1];
  492. lastMatch = currentOpeningToken.matches.pop();
  493. } else {
  494. lastMatch = currentToken.matches.pop();
  495. }
  496. if (lastMatch.isAlternator) {
  497. openenings.push(lastMatch);
  498. } else {
  499. alternator = new MaskToken(false, false, false, true);
  500. alternator.matches.push(lastMatch);
  501. openenings.push(alternator);
  502. }
  503. break;
  504. default:
  505. defaultCase();
  506. }
  507. }
  508. while (openenings.length > 0) {
  509. openingToken = openenings.pop();
  510. currentToken.matches.push(openingToken);
  511. }
  512. if (currentToken.matches.length > 0) {
  513. verifyGroupMarker(currentToken);
  514. maskTokens.push(currentToken);
  515. }
  516. if (opts.numericInput) {
  517. reverseTokens(maskTokens[0]);
  518. }
  519. // console.log(JSON.stringify(maskTokens));
  520. return maskTokens;
  521. }
  522. };
  523. //apply defaults, definitions, aliases
  524. Inputmask.extendDefaults = function (options) {
  525. $.extend(true, Inputmask.prototype.defaults, options);
  526. };
  527. Inputmask.extendDefinitions = function (definition) {
  528. $.extend(true, Inputmask.prototype.defaults.definitions, definition);
  529. };
  530. Inputmask.extendAliases = function (alias) {
  531. $.extend(true, Inputmask.prototype.defaults.aliases, alias);
  532. };
  533. //static fn on inputmask
  534. Inputmask.format = function (value, options, metadata) {
  535. return Inputmask(options).format(value, metadata);
  536. };
  537. Inputmask.unmask = function (value, options) {
  538. return Inputmask(options).unmaskedvalue(value);
  539. };
  540. Inputmask.isValid = function (value, options) {
  541. return Inputmask(options).isValid(value);
  542. };
  543. Inputmask.remove = function (elems) {
  544. $.each(elems, function (ndx, el) {
  545. if (el.inputmask) el.inputmask.remove();
  546. });
  547. };
  548. Inputmask.escapeRegex = function (str) {
  549. var specials = ["/", ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\", "$", "^"];
  550. return str.replace(new RegExp("(\\" + specials.join("|\\") + ")", "gim"), "\\$1");
  551. };
  552. Inputmask.keyCode = {
  553. ALT: 18,
  554. BACKSPACE: 8,
  555. BACKSPACE_SAFARI: 127,
  556. CAPS_LOCK: 20,
  557. COMMA: 188,
  558. COMMAND: 91,
  559. COMMAND_LEFT: 91,
  560. COMMAND_RIGHT: 93,
  561. CONTROL: 17,
  562. DELETE: 46,
  563. DOWN: 40,
  564. END: 35,
  565. ENTER: 13,
  566. ESCAPE: 27,
  567. HOME: 36,
  568. INSERT: 45,
  569. LEFT: 37,
  570. MENU: 93,
  571. NUMPAD_ADD: 107,
  572. NUMPAD_DECIMAL: 110,
  573. NUMPAD_DIVIDE: 111,
  574. NUMPAD_ENTER: 108,
  575. NUMPAD_MULTIPLY: 106,
  576. NUMPAD_SUBTRACT: 109,
  577. PAGE_DOWN: 34,
  578. PAGE_UP: 33,
  579. PERIOD: 190,
  580. RIGHT: 39,
  581. SHIFT: 16,
  582. SPACE: 32,
  583. TAB: 9,
  584. UP: 38,
  585. WINDOWS: 91,
  586. X: 88
  587. };
  588. function resolveAlias(aliasStr, options, opts) {
  589. var aliasDefinition = opts.aliases[aliasStr];
  590. if (aliasDefinition) {
  591. if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias, undefined, opts); //alias is another alias
  592. $.extend(true, opts, aliasDefinition); //merge alias definition in the options
  593. $.extend(true, opts, options); //reapply extra given options
  594. return true;
  595. } else //alias not found - try as mask
  596. if (opts.mask === null) {
  597. opts.mask = aliasStr;
  598. }
  599. return false;
  600. }
  601. function generateMaskSet(opts, nocache) {
  602. function generateMask(mask, metadata, opts) {
  603. if (mask === null || mask === "") {
  604. return undefined;
  605. } else {
  606. if (mask.length === 1 && opts.greedy === false && opts.repeat !== 0) {
  607. opts.placeholder = "";
  608. } //hide placeholder with single non-greedy mask
  609. if (opts.repeat > 0 || opts.repeat === "*" || opts.repeat === "+") {
  610. var repeatStart = opts.repeat === "*" ? 0 : (opts.repeat === "+" ? 1 : opts.repeat);
  611. mask = opts.groupmarker.start + mask + opts.groupmarker.end + opts.quantifiermarker.start + repeatStart + "," + opts.repeat + opts.quantifiermarker.end;
  612. }
  613. // console.log(mask);
  614. var masksetDefinition;
  615. if (Inputmask.prototype.masksCache[mask] === undefined || nocache === true) {
  616. masksetDefinition = {
  617. "mask": mask,
  618. "maskToken": Inputmask.prototype.analyseMask(mask, opts),
  619. "validPositions": {},
  620. "_buffer": undefined,
  621. "buffer": undefined,
  622. "tests": {},
  623. "metadata": metadata,
  624. maskLength: undefined
  625. };
  626. if (nocache !== true) {
  627. Inputmask.prototype.masksCache[opts.numericInput ? mask.split("").reverse().join("") : mask] = masksetDefinition;
  628. masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[opts.numericInput ? mask.split("").reverse().join("") : mask]);
  629. }
  630. } else masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[opts.numericInput ? mask.split("").reverse().join("") : mask]);
  631. return masksetDefinition;
  632. }
  633. }
  634. var ms;
  635. if ($.isFunction(opts.mask)) { //allow mask to be a preprocessing fn - should return a valid mask
  636. opts.mask = opts.mask(opts);
  637. }
  638. if ($.isArray(opts.mask)) {
  639. if (opts.mask.length > 1) {
  640. opts.keepStatic = opts.keepStatic === null ? true : opts.keepStatic; //enable by default when passing multiple masks when the option is not explicitly specified
  641. var altMask = opts.groupmarker.start;
  642. $.each(opts.numericInput ? opts.mask.reverse() : opts.mask, function (ndx, msk) {
  643. if (altMask.length > 1) {
  644. altMask += opts.groupmarker.end + opts.alternatormarker + opts.groupmarker.start;
  645. }
  646. if (msk.mask !== undefined && !$.isFunction(msk.mask)) {
  647. altMask += msk.mask;
  648. } else {
  649. altMask += msk;
  650. }
  651. });
  652. altMask += opts.groupmarker.end;
  653. // console.log(altMask);
  654. return generateMask(altMask, opts.mask, opts);
  655. } else opts.mask = opts.mask.pop();
  656. }
  657. if (opts.mask) {
  658. if (opts.mask.mask !== undefined && !$.isFunction(opts.mask.mask)) {
  659. ms = generateMask(opts.mask.mask, opts.mask, opts);
  660. } else {
  661. ms = generateMask(opts.mask, opts.mask, opts);
  662. }
  663. }
  664. return ms;
  665. };
  666. //masking scope
  667. //actionObj definition see below
  668. function maskScope(actionObj, maskset, opts) {
  669. maskset = maskset || this.maskset;
  670. opts = opts || this.opts;
  671. var el = this.el,
  672. isRTL = this.isRTL,
  673. undoValue,
  674. $el,
  675. skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
  676. skipInputEvent = false, //skip when triggered from within inputmask
  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) {
  1685. if (input.inputmask === undefined) {
  1686. return input.value;
  1687. }
  1688. if (input.inputmask && input.inputmask.refreshValue) { //forced refresh from the value form.reset
  1689. EventHandlers.setValueEvent.call(input);
  1690. }
  1691. }
  1692. var umValue = [],
  1693. vps = getMaskSet().validPositions;
  1694. for (var pndx in vps) {
  1695. if (vps[pndx].match && vps[pndx].match.fn != null) {
  1696. umValue.push(vps[pndx].input);
  1697. }
  1698. }
  1699. var unmaskedValue = umValue.length === 0 ? "" : (isRTL ? umValue.reverse() : umValue).join("");
  1700. if ($.isFunction(opts.onUnMask)) {
  1701. var bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join("");
  1702. unmaskedValue = (opts.onUnMask(bufferValue, unmaskedValue, opts) || unmaskedValue);
  1703. }
  1704. return unmaskedValue;
  1705. }
  1706. function caret(input, begin, end, notranslate) {
  1707. function translatePosition(pos) {
  1708. if (notranslate !== true && isRTL && typeof pos === "number" && (!opts.greedy || opts.placeholder !== "")) {
  1709. 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)
  1710. pos = bffrLght - pos;
  1711. }
  1712. return pos;
  1713. }
  1714. var range;
  1715. if (typeof begin === "number") {
  1716. begin = translatePosition(begin);
  1717. end = translatePosition(end);
  1718. end = (typeof end == "number") ? end : begin;
  1719. // if (!$(input).is(":visible")) {
  1720. // return;
  1721. // }
  1722. var scrollCalc = parseInt(((input.ownerDocument.defaultView || window).getComputedStyle ? (input.ownerDocument.defaultView || window).getComputedStyle(input, null) : input.currentStyle).fontSize) * end;
  1723. input.scrollLeft = scrollCalc > input.scrollWidth ? scrollCalc : 0;
  1724. if (!mobile && opts.insertMode === false && begin === end) end++; //set visualization for insert/overwrite mode
  1725. if (input.setSelectionRange) {
  1726. input.selectionStart = begin;
  1727. input.selectionEnd = end;
  1728. } else if (window.getSelection) {
  1729. range = document.createRange();
  1730. if (input.firstChild === undefined || input.firstChild === null) {
  1731. var textNode = document.createTextNode("");
  1732. input.appendChild(textNode);
  1733. }
  1734. range.setStart(input.firstChild, begin < input.inputmask._valueGet().length ? begin : input.inputmask._valueGet().length);
  1735. range.setEnd(input.firstChild, end < input.inputmask._valueGet().length ? end : input.inputmask._valueGet().length);
  1736. range.collapse(true);
  1737. var sel = window.getSelection();
  1738. sel.removeAllRanges();
  1739. sel.addRange(range);
  1740. //input.focus();
  1741. } else if (input.createTextRange) {
  1742. range = input.createTextRange();
  1743. range.collapse(true);
  1744. range.moveEnd("character", end);
  1745. range.moveStart("character", begin);
  1746. range.select();
  1747. }
  1748. renderColorMask(input, undefined, {begin: begin, end: end});
  1749. } else {
  1750. if (input.setSelectionRange) {
  1751. begin = input.selectionStart;
  1752. end = input.selectionEnd;
  1753. } else if (window.getSelection) {
  1754. range = window.getSelection().getRangeAt(0);
  1755. if (range.commonAncestorContainer.parentNode === input || range.commonAncestorContainer === input) {
  1756. begin = range.startOffset;
  1757. end = range.endOffset;
  1758. }
  1759. } else if (document.selection && document.selection.createRange) {
  1760. range = document.selection.createRange();
  1761. begin = 0 - range.duplicate().moveStart("character", -input.inputmask._valueGet().length);
  1762. end = begin + range.text.length;
  1763. }
  1764. /*eslint-disable consistent-return */
  1765. return {
  1766. "begin": translatePosition(begin),
  1767. "end": translatePosition(end)
  1768. };
  1769. /*eslint-enable consistent-return */
  1770. }
  1771. }
  1772. function determineLastRequiredPosition(returnDefinition) {
  1773. var buffer = getBuffer(),
  1774. bl = buffer.length,
  1775. pos, lvp = getLastValidPosition(),
  1776. positions = {},
  1777. lvTest = getMaskSet().validPositions[lvp],
  1778. ndxIntlzr = lvTest !== undefined ? lvTest.locator.slice() : undefined,
  1779. testPos;
  1780. for (pos = lvp + 1; pos < buffer.length; pos++) {
  1781. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  1782. ndxIntlzr = testPos.locator.slice();
  1783. positions[pos] = $.extend(true, {}, testPos);
  1784. }
  1785. var lvTestAlt = lvTest && lvTest.alternation !== undefined ? lvTest.locator[lvTest.alternation] : undefined;
  1786. for (pos = bl - 1; pos > lvp; pos--) {
  1787. testPos = positions[pos];
  1788. if ((testPos.match.optionality ||
  1789. testPos.match.optionalQuantifier ||
  1790. (lvTestAlt &&
  1791. ((lvTestAlt !== positions[pos].locator[lvTest.alternation] && testPos.match.fn != null) ||
  1792. (testPos.match.fn === null && testPos.locator[lvTest.alternation] && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAlt.toString().split(",")) && getTests(pos)[0].def !== "")))) &&
  1793. buffer[pos] === getPlaceholder(pos, testPos.match)) {
  1794. bl--;
  1795. } else break;
  1796. }
  1797. return returnDefinition ? {
  1798. "l": bl,
  1799. "def": positions[bl] ? positions[bl].match : undefined
  1800. } : bl;
  1801. }
  1802. function clearOptionalTail(buffer) {
  1803. var rl = determineLastRequiredPosition(),
  1804. validPos, bl = buffer.length;
  1805. while (rl < bl && !isMask(rl + 1) && (validPos = getTest(rl + 1)) && validPos.match.optionality !== true && validPos.match.optionalQuantifier !== true) {
  1806. rl++;
  1807. }
  1808. while ((validPos = getTest(rl - 1)) && validPos.match.optionality && validPos.input === opts.skipOptionalPartCharacter) {
  1809. rl--;
  1810. }
  1811. buffer.splice(rl);
  1812. return buffer;
  1813. }
  1814. function isComplete(buffer) { //return true / false / undefined (repeat *)
  1815. if ($.isFunction(opts.isComplete)) return opts.isComplete(buffer, opts);
  1816. if (opts.repeat === "*") return undefined;
  1817. var complete = false,
  1818. lrp = determineLastRequiredPosition(true),
  1819. aml = seekPrevious(lrp.l);
  1820. if (lrp.def === undefined || lrp.def.newBlockMarker || lrp.def.optionality || lrp.def.optionalQuantifier) {
  1821. complete = true;
  1822. for (var i = 0; i <= aml; i++) {
  1823. var test = getTestTemplate(i).match;
  1824. if ((test.fn !== null && getMaskSet().validPositions[i] === undefined && test.optionality !== true && test.optionalQuantifier !== true) || (test.fn === null && buffer[i] !== getPlaceholder(i, test))) {
  1825. complete = false;
  1826. break;
  1827. }
  1828. }
  1829. }
  1830. return complete;
  1831. }
  1832. function handleRemove(input, k, pos, strict) {
  1833. function generalize() {
  1834. if (opts.keepStatic) {
  1835. var validInputs = [],
  1836. lastAlt = getLastValidPosition(-1, true), positionsClone = $.extend(true, {}, getMaskSet().validPositions),
  1837. prevAltPos = getMaskSet().validPositions[lastAlt];
  1838. //find last alternation
  1839. for (; lastAlt >= 0; lastAlt--) {
  1840. var altPos = getMaskSet().validPositions[lastAlt];
  1841. if (altPos) {
  1842. if (altPos.generatedInput !== true && /[0-9a-bA-Z]/.test(altPos.input)) {
  1843. validInputs.push(altPos.input);
  1844. }
  1845. delete getMaskSet().validPositions[lastAlt];
  1846. if (altPos.alternation !== undefined && altPos.locator[altPos.alternation] !== prevAltPos.locator[altPos.alternation]) {
  1847. break;
  1848. }
  1849. prevAltPos = altPos;
  1850. }
  1851. }
  1852. if (lastAlt > -1) {
  1853. getMaskSet().p = seekNext(getLastValidPosition(-1, true));
  1854. while (validInputs.length > 0) {
  1855. var keypress = new $.Event("keypress");
  1856. keypress.which = validInputs.pop().charCodeAt(0);
  1857. EventHandlers.keypressEvent.call(input, keypress, true, false, false, getMaskSet().p);
  1858. }
  1859. } else getMaskSet().validPositions = $.extend(true, {}, positionsClone); //restore original positions
  1860. }
  1861. }
  1862. if (opts.numericInput || isRTL) {
  1863. if (k === Inputmask.keyCode.BACKSPACE) {
  1864. k = Inputmask.keyCode.DELETE;
  1865. } else if (k === Inputmask.keyCode.DELETE) {
  1866. k = Inputmask.keyCode.BACKSPACE;
  1867. }
  1868. if (isRTL) {
  1869. var pend = pos.end;
  1870. pos.end = pos.begin;
  1871. pos.begin = pend;
  1872. }
  1873. }
  1874. if (k === Inputmask.keyCode.BACKSPACE && (pos.end - pos.begin < 1 || opts.insertMode === false)) {
  1875. pos.begin = seekPrevious(pos.begin);
  1876. if (getMaskSet().validPositions[pos.begin] !== undefined && (getMaskSet().validPositions[pos.begin].input === opts.groupSeparator || getMaskSet().validPositions[pos.begin].input === opts.radixPoint)) {
  1877. pos.begin--;
  1878. }
  1879. } else if (k === Inputmask.keyCode.DELETE && pos.begin === pos.end) {
  1880. pos.end = isMask(pos.end, true) ? pos.end + 1 : seekNext(pos.end) + 1;
  1881. if (getMaskSet().validPositions[pos.begin] !== undefined && (getMaskSet().validPositions[pos.begin].input === opts.groupSeparator || getMaskSet().validPositions[pos.begin].input === opts.radixPoint)) {
  1882. pos.end++;
  1883. }
  1884. }
  1885. stripValidPositions(pos.begin, pos.end, false, strict);
  1886. if (strict !== true) {
  1887. generalize(); //revert the alternation
  1888. }
  1889. var lvp = getLastValidPosition(pos.begin, true);
  1890. if (lvp < pos.begin) {
  1891. //if (lvp === -1) resetMaskSet();
  1892. getMaskSet().p = seekNext(lvp);
  1893. } else if (strict !== true) {
  1894. getMaskSet().p = pos.begin;
  1895. }
  1896. }
  1897. var EventRuler = {
  1898. on: function (input, eventName, eventHandler) {
  1899. var ev = function (e) {
  1900. // console.log("triggered " + e.type);
  1901. if (this.inputmask === undefined && this.nodeName !== "FORM") { //happens when cloning an object with jquery.clone
  1902. var imOpts = $.data(this, "_inputmask_opts");
  1903. if (imOpts) (new Inputmask(imOpts)).mask(this);
  1904. else EventRuler.off(this);
  1905. } 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))))) {
  1906. e.preventDefault();
  1907. } else {
  1908. switch (e.type) {
  1909. case "input":
  1910. if (skipInputEvent === true) {
  1911. skipInputEvent = false;
  1912. return e.preventDefault();
  1913. }
  1914. break;
  1915. case "keydown":
  1916. //Safari 5.1.x - modal dialog fires keypress twice workaround
  1917. skipKeyPressEvent = false;
  1918. skipInputEvent = false;
  1919. break;
  1920. case "keypress":
  1921. if (skipKeyPressEvent === true) {
  1922. return e.preventDefault();
  1923. }
  1924. skipKeyPressEvent = true;
  1925. break;
  1926. case "click":
  1927. if (iemobile || iphone) {
  1928. var that = this, args = arguments;
  1929. setTimeout(function () {
  1930. eventHandler.apply(that, args);
  1931. }, 0);
  1932. return false;
  1933. }
  1934. break;
  1935. }
  1936. // console.log("executed " + e.type);
  1937. var returnVal = eventHandler.apply(this, arguments);
  1938. if (returnVal === false) {
  1939. e.preventDefault();
  1940. e.stopPropagation();
  1941. }
  1942. return returnVal;
  1943. }
  1944. };
  1945. //keep instance of the event
  1946. input.inputmask.events[eventName] = input.inputmask.events[eventName] || [];
  1947. input.inputmask.events[eventName].push(ev);
  1948. if ($.inArray(eventName, ["submit", "reset"]) !== -1) {
  1949. if (input.form != null) $(input.form).on(eventName, ev);
  1950. } else {
  1951. $(input).on(eventName, ev);
  1952. }
  1953. },
  1954. off: function (input, event) {
  1955. if (input.inputmask && input.inputmask.events) {
  1956. var events;
  1957. if (event) {
  1958. events = [];
  1959. events[event] = input.inputmask.events[event];
  1960. } else {
  1961. events = input.inputmask.events;
  1962. }
  1963. $.each(events, function (eventName, evArr) {
  1964. while (evArr.length > 0) {
  1965. var ev = evArr.pop();
  1966. if ($.inArray(eventName, ["submit", "reset"]) !== -1) {
  1967. if (input.form != null) $(input.form).off(eventName, ev);
  1968. } else {
  1969. $(input).off(eventName, ev);
  1970. }
  1971. }
  1972. delete input.inputmask.events[eventName];
  1973. });
  1974. }
  1975. }
  1976. };
  1977. var EventHandlers = {
  1978. keydownEvent: function (e) {
  1979. function isInputEventSupported(eventName) {
  1980. var el = document.createElement("input"),
  1981. evName = "on" + eventName,
  1982. isSupported = (evName in el);
  1983. if (!isSupported) {
  1984. el.setAttribute(evName, "return;");
  1985. isSupported = typeof el[evName] == "function";
  1986. }
  1987. el = null;
  1988. return isSupported;
  1989. }
  1990. var input = this,
  1991. $input = $(input),
  1992. k = e.keyCode,
  1993. pos = caret(input);
  1994. //backspace, delete, and escape get special treatment
  1995. 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
  1996. e.preventDefault(); //stop default action but allow propagation
  1997. handleRemove(input, k, pos);
  1998. writeBuffer(input, getBuffer(true), getMaskSet().p, e, input.inputmask._valueGet() !== getBuffer().join(""));
  1999. if (input.inputmask._valueGet() === getBufferTemplate().join("")) {
  2000. $input.trigger("cleared");
  2001. } else if (isComplete(getBuffer()) === true) {
  2002. $input.trigger("complete");
  2003. }
  2004. } else if (k === Inputmask.keyCode.END || k === Inputmask.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  2005. e.preventDefault();
  2006. var caretPos = seekNext(getLastValidPosition());
  2007. if (!opts.insertMode && caretPos === getMaskSet().maskLength && !e.shiftKey) caretPos--;
  2008. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos, true);
  2009. } else if ((k === Inputmask.keyCode.HOME && !e.shiftKey) || k === Inputmask.keyCode.PAGE_UP) { //Home or page_up
  2010. e.preventDefault();
  2011. caret(input, 0, e.shiftKey ? pos.begin : 0, true);
  2012. } else if (((opts.undoOnEscape && k === Inputmask.keyCode.ESCAPE) || (k === 90 && e.ctrlKey)) && e.altKey !== true) { //escape && undo && #762
  2013. checkVal(input, true, false, undoValue.split(""));
  2014. $input.trigger("click");
  2015. } else if (k === Inputmask.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
  2016. opts.insertMode = !opts.insertMode;
  2017. caret(input, !opts.insertMode && pos.begin === getMaskSet().maskLength ? pos.begin - 1 : pos.begin);
  2018. } else if (opts.tabThrough === true && k === Inputmask.keyCode.TAB) {
  2019. if (e.shiftKey === true) {
  2020. if (getTest(pos.begin).match.fn === null) {
  2021. pos.begin = seekNext(pos.begin);
  2022. }
  2023. pos.end = seekPrevious(pos.begin, true);
  2024. pos.begin = seekPrevious(pos.end, true);
  2025. } else {
  2026. pos.begin = seekNext(pos.begin, true);
  2027. pos.end = seekNext(pos.begin, true);
  2028. if (pos.end < getMaskSet().maskLength) pos.end--;
  2029. }
  2030. if (pos.begin < getMaskSet().maskLength) {
  2031. e.preventDefault();
  2032. caret(input, pos.begin, pos.end);
  2033. }
  2034. } else if (!e.shiftKey) {
  2035. if (opts.insertMode === false) {
  2036. if (k === Inputmask.keyCode.RIGHT) {
  2037. setTimeout(function () {
  2038. var caretPos = caret(input);
  2039. caret(input, caretPos.begin);
  2040. }, 0);
  2041. } else if (k === Inputmask.keyCode.LEFT) {
  2042. setTimeout(function () {
  2043. var caretPos = caret(input);
  2044. caret(input, isRTL ? caretPos.begin + 1 : caretPos.begin - 1);
  2045. }, 0);
  2046. }
  2047. }
  2048. }
  2049. opts.onKeyDown.call(this, e, getBuffer(), caret(input).begin, opts);
  2050. ignorable = $.inArray(k, opts.ignorables) !== -1;
  2051. },
  2052. keypressEvent: function (e, checkval, writeOut, strict, ndx) {
  2053. var input = this,
  2054. $input = $(input),
  2055. k = e.which || e.charCode || e.keyCode;
  2056. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  2057. if (k === Inputmask.keyCode.ENTER && undoValue !== getBuffer().join("")) {
  2058. undoValue = getBuffer().join("");
  2059. // e.preventDefault();
  2060. setTimeout(function () {
  2061. $input.trigger("change");
  2062. }, 0);
  2063. }
  2064. return true;
  2065. } else {
  2066. if (k) {
  2067. //special treat the decimal separator
  2068. if (k === 46 && e.shiftKey === false && opts.radixPoint === ",") k = 44;
  2069. var pos = checkval ? {
  2070. begin: ndx,
  2071. end: ndx
  2072. } : caret(input),
  2073. forwardPosition, c = String.fromCharCode(k);
  2074. getMaskSet().writeOutBuffer = true;
  2075. var valResult = isValid(pos, c, strict);
  2076. if (valResult !== false) {
  2077. resetMaskSet(true);
  2078. forwardPosition = valResult.caret !== undefined ? valResult.caret : checkval ? valResult.pos + 1 : seekNext(valResult.pos);
  2079. getMaskSet().p = forwardPosition; //needed for checkval
  2080. }
  2081. if (writeOut !== false) {
  2082. var self = this;
  2083. setTimeout(function () {
  2084. opts.onKeyValidation.call(self, k, valResult, opts);
  2085. }, 0);
  2086. if (getMaskSet().writeOutBuffer && valResult !== false) {
  2087. var buffer = getBuffer();
  2088. writeBuffer(input, buffer, (opts.numericInput && valResult.caret === undefined) ? seekPrevious(forwardPosition) : forwardPosition, e, checkval !== true);
  2089. if (checkval !== true) {
  2090. setTimeout(function () { //timeout needed for IE
  2091. if (isComplete(buffer) === true) $input.trigger("complete");
  2092. }, 0);
  2093. }
  2094. }
  2095. }
  2096. e.preventDefault();
  2097. if (checkval) {
  2098. valResult.forwardPosition = forwardPosition;
  2099. return valResult;
  2100. }
  2101. }
  2102. }
  2103. },
  2104. pasteEvent: function (e) {
  2105. var input = this,
  2106. ev = e.originalEvent || e,
  2107. $input = $(input),
  2108. inputValue = input.inputmask._valueGet(true),
  2109. caretPos = caret(input),
  2110. tempValue;
  2111. if (isRTL) {
  2112. tempValue = caretPos.end;
  2113. caretPos.end = caretPos.begin;
  2114. caretPos.begin = tempValue;
  2115. }
  2116. var valueBeforeCaret = inputValue.substr(0, caretPos.begin),
  2117. valueAfterCaret = inputValue.substr(caretPos.end, inputValue.length);
  2118. if (valueBeforeCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(0, caretPos.begin).join("")) valueBeforeCaret = "";
  2119. if (valueAfterCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(caretPos.end).join("")) valueAfterCaret = "";
  2120. if (isRTL) {
  2121. tempValue = valueBeforeCaret;
  2122. valueBeforeCaret = valueAfterCaret;
  2123. valueAfterCaret = tempValue;
  2124. }
  2125. if (window.clipboardData && window.clipboardData.getData) { // IE
  2126. inputValue = valueBeforeCaret + window.clipboardData.getData("Text") + valueAfterCaret;
  2127. } else if (ev.clipboardData && ev.clipboardData.getData) {
  2128. inputValue = valueBeforeCaret + ev.clipboardData.getData("text/plain") + valueAfterCaret;
  2129. } else return true; //allow native paste event as fallback ~ masking will continue by inputfallback
  2130. var pasteValue = inputValue;
  2131. if ($.isFunction(opts.onBeforePaste)) {
  2132. pasteValue = opts.onBeforePaste(inputValue, opts);
  2133. if (pasteValue === false) {
  2134. return e.preventDefault();
  2135. }
  2136. if (!pasteValue) {
  2137. pasteValue = inputValue;
  2138. }
  2139. }
  2140. checkVal(input, false, false, isRTL ? pasteValue.split("").reverse() : pasteValue.toString().split(""));
  2141. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()), e, undoValue !== getBuffer().join(""));
  2142. if (isComplete(getBuffer()) === true) {
  2143. $input.trigger("complete");
  2144. }
  2145. return e.preventDefault();
  2146. },
  2147. inputFallBackEvent: function (e) { //fallback when keypress fails
  2148. var input = this,
  2149. inputValue = input.inputmask._valueGet();
  2150. //console.log(inputValue);
  2151. if (getBuffer().join("") !== inputValue) {
  2152. var caretPos = caret(input);
  2153. inputValue = inputValue.replace(new RegExp("(" + Inputmask.escapeRegex(getBufferTemplate().join("")) + ")*"), "");
  2154. if (iemobile) { //iemobile just set the character at the end althought the caret position is correctly set
  2155. var inputChar = inputValue.replace(getBuffer().join(""), "");
  2156. if (inputChar.length === 1) {
  2157. var keypress = new $.Event("keypress");
  2158. keypress.which = inputChar.charCodeAt(0);
  2159. EventHandlers.keypressEvent.call(input, keypress, true, true, false, getMaskSet().validPositions[caretPos.begin - 1] ? caretPos.begin : caretPos.begin - 1);
  2160. return false;
  2161. }
  2162. }
  2163. if (caretPos.begin > inputValue.length) {
  2164. caret(input, inputValue.length);
  2165. caretPos = caret(input);
  2166. }
  2167. //detect & treat possible backspace before static
  2168. if ((getBuffer().length - inputValue.length) === 1 && inputValue.charAt(caretPos.begin) !== getBuffer()[caretPos.begin] && inputValue.charAt(caretPos.begin + 1) !== getBuffer()[caretPos.begin] && !isMask(caretPos.begin)) {
  2169. e.keyCode = Inputmask.keyCode.BACKSPACE;
  2170. EventHandlers.keydownEvent.call(input, e);
  2171. } else {
  2172. var lvp = getLastValidPosition() + 1;
  2173. var bufferTemplate = getBufferTemplate().join(""); //getBuffer().slice(lvp).join('');
  2174. while (inputValue.match(Inputmask.escapeRegex(bufferTemplate) + "$") === null) {
  2175. bufferTemplate = bufferTemplate.slice(1);
  2176. }
  2177. inputValue = inputValue.replace(bufferTemplate, "");
  2178. inputValue = inputValue.split("");
  2179. checkVal(input, true, false, inputValue, e, caretPos.begin < lvp);
  2180. if (isComplete(getBuffer()) === true) {
  2181. $(input).trigger("complete");
  2182. }
  2183. }
  2184. e.preventDefault();
  2185. }
  2186. },
  2187. setValueEvent: function (e) {
  2188. this.inputmask.refreshValue = false;
  2189. var input = this,
  2190. value = input.inputmask._valueGet();
  2191. checkVal(input, true, false, ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(value, opts) || value) : value).split(""));
  2192. undoValue = getBuffer().join("");
  2193. if ((opts.clearMaskOnLostFocus || opts.clearIncomplete) && input.inputmask._valueGet() === getBufferTemplate().join("")) {
  2194. input.inputmask._valueSet("");
  2195. }
  2196. },
  2197. focusEvent: function (e) {
  2198. var input = this,
  2199. nptValue = input.inputmask._valueGet();
  2200. if (opts.showMaskOnFocus && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue === ""))) {
  2201. if (input.inputmask._valueGet() !== getBuffer().join("")) {
  2202. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
  2203. } else if (mouseEnter === false) { //only executed on focus without mouseenter
  2204. caret(input, seekNext(getLastValidPosition()));
  2205. }
  2206. }
  2207. if (opts.positionCaretOnTab === true) {
  2208. EventHandlers.clickEvent.apply(input, [e, true]);
  2209. }
  2210. undoValue = getBuffer().join("");
  2211. },
  2212. mouseleaveEvent: function (e) {
  2213. var input = this;
  2214. mouseEnter = false;
  2215. if (opts.clearMaskOnLostFocus && document.activeElement !== input) {
  2216. var buffer = getBuffer().slice(),
  2217. nptValue = input.inputmask._valueGet();
  2218. if (nptValue !== input.getAttribute("placeholder") && nptValue !== "") {
  2219. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  2220. buffer = [];
  2221. } else { //clearout optional tail of the mask
  2222. clearOptionalTail(buffer);
  2223. }
  2224. writeBuffer(input, buffer);
  2225. }
  2226. }
  2227. },
  2228. clickEvent: function (e, tabbed) {
  2229. function doRadixFocus(clickPos) {
  2230. if (opts.radixPoint !== "") {
  2231. var vps = getMaskSet().validPositions;
  2232. if (vps[clickPos] === undefined || (vps[clickPos].input === getPlaceholder(clickPos))) {
  2233. if (clickPos < seekNext(-1)) return true;
  2234. var radixPos = $.inArray(opts.radixPoint, getBuffer());
  2235. if (radixPos !== -1) {
  2236. for (var vp in vps) {
  2237. if (radixPos < vp && vps[vp].input !== getPlaceholder(vp)) {
  2238. return false;
  2239. }
  2240. }
  2241. return true;
  2242. }
  2243. }
  2244. }
  2245. return false;
  2246. }
  2247. var input = this;
  2248. setTimeout(function () { //needed for Chrome ~ initial selection clears after the clickevent
  2249. if (document.activeElement === input) {
  2250. var selectedCaret = caret(input);
  2251. if (tabbed) selectedCaret.begin = selectedCaret.end;
  2252. if (selectedCaret.begin === selectedCaret.end) {
  2253. switch (opts.positionCaretOnClick) {
  2254. case "none":
  2255. break;
  2256. case "radixFocus":
  2257. if (doRadixFocus(selectedCaret.begin)) {
  2258. var radixPos = $.inArray(opts.radixPoint, getBuffer().join(""));
  2259. caret(input, opts.numericInput ? seekNext(radixPos) : radixPos);
  2260. break;
  2261. }
  2262. default: //lvp:
  2263. var clickPosition = selectedCaret.begin,
  2264. lvclickPosition = getLastValidPosition(clickPosition, true),
  2265. lastPosition = seekNext(lvclickPosition);
  2266. if (clickPosition < lastPosition) {
  2267. caret(input, !isMask(clickPosition) && !isMask(clickPosition - 1) ? seekNext(clickPosition) : clickPosition);
  2268. } else {
  2269. var placeholder = getPlaceholder(lastPosition);
  2270. if ((placeholder !== "" && getBuffer()[lastPosition] !== placeholder && getTest(lastPosition).match.optionalQuantifier !== true) || (!isMask(lastPosition) && getTest(lastPosition).match.def === placeholder)) {
  2271. lastPosition = seekNext(lastPosition);
  2272. }
  2273. caret(input, lastPosition);
  2274. }
  2275. break;
  2276. }
  2277. }
  2278. }
  2279. }, 0);
  2280. },
  2281. dblclickEvent: function (e) {
  2282. var input = this;
  2283. setTimeout(function () {
  2284. caret(input, 0, seekNext(getLastValidPosition()));
  2285. }, 0);
  2286. },
  2287. cutEvent: function (e) {
  2288. var input = this,
  2289. $input = $(input),
  2290. pos = caret(input),
  2291. ev = e.originalEvent || e;
  2292. //correct clipboardData
  2293. var clipboardData = window.clipboardData || ev.clipboardData,
  2294. clipData = isRTL ? getBuffer().slice(pos.end, pos.begin) : getBuffer().slice(pos.begin, pos.end);
  2295. clipboardData.setData("text", isRTL ? clipData.reverse().join("") : clipData.join(""));
  2296. if (document.execCommand) document.execCommand("copy"); // copy selected content to system clipbaord
  2297. handleRemove(input, Inputmask.keyCode.DELETE, pos);
  2298. writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join(""));
  2299. if (input.inputmask._valueGet() === getBufferTemplate().join("")) {
  2300. $input.trigger("cleared");
  2301. }
  2302. },
  2303. blurEvent: function (e) {
  2304. var $input = $(this),
  2305. input = this;
  2306. if (input.inputmask) {
  2307. var nptValue = input.inputmask._valueGet(),
  2308. buffer = getBuffer().slice();
  2309. if (undoValue !== buffer.join("")) {
  2310. setTimeout(function () { //change event should be triggered after the other buffer manipulations on blur
  2311. $input.trigger("change");
  2312. undoValue = buffer.join("");
  2313. }, 0);
  2314. }
  2315. if (nptValue !== "") {
  2316. if (opts.clearMaskOnLostFocus) {
  2317. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  2318. buffer = [];
  2319. } else { //clearout optional tail of the mask
  2320. clearOptionalTail(buffer);
  2321. }
  2322. }
  2323. if (isComplete(buffer) === false) {
  2324. setTimeout(function () {
  2325. $input.trigger("incomplete");
  2326. }, 0);
  2327. if (opts.clearIncomplete) {
  2328. resetMaskSet();
  2329. if (opts.clearMaskOnLostFocus) {
  2330. buffer = [];
  2331. } else {
  2332. buffer = getBufferTemplate().slice();
  2333. }
  2334. }
  2335. }
  2336. writeBuffer(input, buffer, undefined, e);
  2337. }
  2338. }
  2339. },
  2340. mouseenterEvent: function (e) {
  2341. var input = this;
  2342. mouseEnter = true;
  2343. if (document.activeElement !== input && opts.showMaskOnHover) {
  2344. if (input.inputmask._valueGet() !== getBuffer().join("")) {
  2345. writeBuffer(input, getBuffer());
  2346. }
  2347. }
  2348. },
  2349. submitEvent: function (e) { //trigger change on submit if any
  2350. if (undoValue !== getBuffer().join("")) {
  2351. $el.trigger("change");
  2352. }
  2353. if (opts.clearMaskOnLostFocus && getLastValidPosition() === -1 && el.inputmask._valueGet && el.inputmask._valueGet() === getBufferTemplate().join("")) {
  2354. el.inputmask._valueSet(""); //clear masktemplete on submit and still has focus
  2355. }
  2356. if (opts.removeMaskOnSubmit) {
  2357. el.inputmask._valueSet(el.inputmask.unmaskedvalue(), true);
  2358. setTimeout(function () {
  2359. writeBuffer(el, getBuffer());
  2360. }, 0);
  2361. }
  2362. },
  2363. resetEvent: function (e) {
  2364. el.inputmask.refreshValue = true; //indicate a forced refresh when there is a call to the value before leaving the triggering event fn
  2365. setTimeout(function () {
  2366. $el.trigger("setvalue");
  2367. }, 0);
  2368. }
  2369. };
  2370. function initializeColorMask(input) {
  2371. function findCaretPos(clientx) {
  2372. //calculate text width
  2373. var e = document.createElement('span'), caretPos;
  2374. for (var style in computedStyle) { //clone styles
  2375. if (isNaN(style) && style.indexOf("font") !== -1) {
  2376. e.style[style] = computedStyle[style];
  2377. }
  2378. }
  2379. e.style.textTransform = computedStyle.textTransform;
  2380. e.style.letterSpacing = computedStyle.letterSpacing;
  2381. e.style.position = "absolute";
  2382. e.style.height = "auto";
  2383. e.style.width = "auto";
  2384. e.style.visibility = "hidden";
  2385. e.style.whiteSpace = "nowrap";
  2386. document.body.appendChild(e);
  2387. var inputText = input.inputmask._valueGet(), previousWidth = 0, itl;
  2388. for (caretPos = 0, itl = inputText.length; caretPos <= itl; caretPos++) {
  2389. e.innerHTML += inputText.charAt(caretPos) || "_";
  2390. if (e.offsetWidth >= clientx) {
  2391. var offset1 = (clientx - previousWidth);
  2392. var offset2 = e.offsetWidth - clientx;
  2393. e.innerHTML = inputText.charAt(caretPos);
  2394. offset1 -= (e.offsetWidth / 3);
  2395. caretPos = offset1 < offset2 ? caretPos - 1 : caretPos;
  2396. break;
  2397. }
  2398. previousWidth = e.offsetWidth;
  2399. }
  2400. document.body.removeChild(e);
  2401. return caretPos;
  2402. }
  2403. function position() {
  2404. colorMask.style.position = "absolute";
  2405. colorMask.style.top = offset.top + "px";
  2406. colorMask.style.left = offset.left + "px";
  2407. colorMask.style.width = parseInt(input.offsetWidth) - parseInt(computedStyle.paddingLeft) - parseInt(computedStyle.paddingRight) - parseInt(computedStyle.borderLeftWidth) - parseInt(computedStyle.borderRightWidth) + "px";
  2408. colorMask.style.height = parseInt(input.offsetHeight) - parseInt(computedStyle.paddingTop) - parseInt(computedStyle.paddingBottom) - parseInt(computedStyle.borderTopWidth) - parseInt(computedStyle.borderBottomWidth) + "px";
  2409. colorMask.style.lineHeight = colorMask.style.height;
  2410. colorMask.style.zIndex = isNaN(computedStyle.zIndex) ? -1 : computedStyle.zIndex - 1;
  2411. colorMask.style.webkitAppearance = "textfield";
  2412. colorMask.style.mozAppearance = "textfield";
  2413. colorMask.style.Appearance = "textfield";
  2414. }
  2415. var offset = $(input).position(),
  2416. computedStyle = (input.ownerDocument.defaultView || window).getComputedStyle(input, null),
  2417. parentNode = input.parentNode;
  2418. colorMask = document.createElement("div");
  2419. document.body.appendChild(colorMask); //insert at body to prevent css clash :last-child for example
  2420. for (var style in computedStyle) { //clone styles
  2421. if (isNaN(style) && style !== "cssText" && style.indexOf("webkit") == -1) {
  2422. colorMask.style[style] = computedStyle[style];
  2423. }
  2424. }
  2425. //restyle input
  2426. input.style.backgroundColor = "transparent";
  2427. input.style.color = "transparent";
  2428. input.style.webkitAppearance = "caret";
  2429. input.style.mozAppearance = "caret";
  2430. input.style.Appearance = "caret";
  2431. position();
  2432. //event passthrough
  2433. $(window).on("resize", function (e) {
  2434. offset = $(input).position();
  2435. computedStyle = (input.ownerDocument.defaultView || window).getComputedStyle(input, null);
  2436. position();
  2437. });
  2438. $(input).on("click", function (e) {
  2439. caret(input, findCaretPos(e.clientX));
  2440. return EventHandlers.clickEvent.call(this, [e]);
  2441. });
  2442. $(input).on("keydown", function (e) {
  2443. if (!e.shiftKey && opts.insertMode !== false) {
  2444. setTimeout(function () {
  2445. renderColorMask(input);
  2446. }, 0);
  2447. }
  2448. });
  2449. }
  2450. function renderColorMask(input, buffer, caretPos) {
  2451. function handleStatic() {
  2452. if (!isStatic && (test.fn === null || testPos.input === undefined)) {
  2453. isStatic = true;
  2454. maskTemplate += "<span class='im-static''>"
  2455. } else if (isStatic && (test.fn !== null && testPos.input !== undefined)) {
  2456. isStatic = false;
  2457. maskTemplate += "</span>"
  2458. }
  2459. }
  2460. if (colorMask !== undefined) {
  2461. buffer = buffer || getBuffer();
  2462. if (caretPos === undefined) {
  2463. caretPos = caret(input);
  2464. } else if (caretPos.begin === undefined) {
  2465. caretPos = {begin: caretPos, end: caretPos};
  2466. }
  2467. var maskTemplate = "", isStatic = false;
  2468. if (buffer != "") {
  2469. var ndxIntlzr, pos = 0,
  2470. test, testPos, lvp = getLastValidPosition();
  2471. do {
  2472. if (pos === caretPos.begin && document.activeElement === input) {
  2473. maskTemplate += "<span class='im-caret' style='border-right-width: 1px;border-right-style: solid;'></span>";
  2474. }
  2475. if (getMaskSet().validPositions[pos]) {
  2476. testPos = getMaskSet().validPositions[pos];
  2477. test = testPos.match;
  2478. ndxIntlzr = testPos.locator.slice();
  2479. handleStatic();
  2480. maskTemplate += testPos.input;
  2481. } else {
  2482. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  2483. test = testPos.match;
  2484. ndxIntlzr = testPos.locator.slice();
  2485. if (opts.jitMasking === false || pos < lvp || (typeof opts.jitMasking === "number" && isFinite(opts.jitMasking) && opts.jitMasking > pos)) {
  2486. handleStatic();
  2487. maskTemplate += getPlaceholder(pos, test);
  2488. }
  2489. }
  2490. pos++;
  2491. } while ((maxLength === undefined || pos < maxLength) && (test.fn !== null || test.def !== "") || lvp > pos);
  2492. }
  2493. colorMask.innerHTML = maskTemplate;
  2494. }
  2495. }
  2496. function mask(elem) {
  2497. function isElementTypeSupported(input, opts) {
  2498. function patchValueProperty(npt) {
  2499. var valueGet;
  2500. var valueSet;
  2501. function patchValhook(type) {
  2502. if ($.valHooks && ($.valHooks[type] === undefined || $.valHooks[type].inputmaskpatch !== true)) {
  2503. var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) {
  2504. return elem.value;
  2505. };
  2506. var valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
  2507. elem.value = value;
  2508. return elem;
  2509. };
  2510. $.valHooks[type] = {
  2511. get: function (elem) {
  2512. if (elem.inputmask) {
  2513. if (elem.inputmask.opts.autoUnmask) {
  2514. return elem.inputmask.unmaskedvalue();
  2515. } else {
  2516. var result = valhookGet(elem);
  2517. return getLastValidPosition(undefined, undefined, elem.inputmask.maskset.validPositions) !== -1 || opts.nullable !== true ? result : "";
  2518. }
  2519. } else return valhookGet(elem);
  2520. },
  2521. set: function (elem, value) {
  2522. var $elem = $(elem),
  2523. result;
  2524. result = valhookSet(elem, value);
  2525. if (elem.inputmask) {
  2526. $elem.trigger("setvalue");
  2527. }
  2528. return result;
  2529. },
  2530. inputmaskpatch: true
  2531. };
  2532. }
  2533. }
  2534. function getter() {
  2535. if (this.inputmask) {
  2536. return this.inputmask.opts.autoUnmask ?
  2537. this.inputmask.unmaskedvalue() :
  2538. (getLastValidPosition() !== -1 || opts.nullable !== true ?
  2539. (document.activeElement === this && opts.clearMaskOnLostFocus ?
  2540. (isRTL ? clearOptionalTail(getBuffer().slice()).reverse() : clearOptionalTail(getBuffer().slice())).join("") :
  2541. valueGet.call(this)) :
  2542. "");
  2543. } else return valueGet.call(this);
  2544. }
  2545. function setter(value) {
  2546. valueSet.call(this, value);
  2547. if (this.inputmask) {
  2548. $(this).trigger("setvalue");
  2549. }
  2550. }
  2551. function installNativeValueSetFallback(npt) {
  2552. EventRuler.on(npt, "mouseenter", function (event) {
  2553. var $input = $(this),
  2554. input = this,
  2555. value = input.inputmask._valueGet();
  2556. if (value !== getBuffer().join("") /*&& getLastValidPosition() > 0*/) {
  2557. $input.trigger("setvalue");
  2558. }
  2559. });
  2560. }
  2561. if (!npt.inputmask.__valueGet) {
  2562. if (opts.noValuePatching !== true) {
  2563. if (Object.getOwnPropertyDescriptor) {
  2564. if (typeof Object.getPrototypeOf !== "function") {
  2565. Object.getPrototypeOf = typeof "test".__proto__ === "object" ? function (object) {
  2566. return object.__proto__;
  2567. } : function (object) {
  2568. return object.constructor.prototype;
  2569. };
  2570. }
  2571. var valueProperty = Object.getPrototypeOf ? Object.getOwnPropertyDescriptor(Object.getPrototypeOf(npt), "value") : undefined;
  2572. if (valueProperty && valueProperty.get && valueProperty.set) {
  2573. valueGet = valueProperty.get;
  2574. valueSet = valueProperty.set;
  2575. Object.defineProperty(npt, "value", {
  2576. get: getter,
  2577. set: setter,
  2578. configurable: true
  2579. });
  2580. } else if (npt.tagName !== "INPUT") {
  2581. valueGet = function () {
  2582. return this.textContent;
  2583. };
  2584. valueSet = function (value) {
  2585. this.textContent = value;
  2586. };
  2587. Object.defineProperty(npt, "value", {
  2588. get: getter,
  2589. set: setter,
  2590. configurable: true
  2591. });
  2592. }
  2593. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  2594. valueGet = npt.__lookupGetter__("value");
  2595. valueSet = npt.__lookupSetter__("value");
  2596. npt.__defineGetter__("value", getter);
  2597. npt.__defineSetter__("value", setter);
  2598. }
  2599. npt.inputmask.__valueGet = valueGet; //store native property getter
  2600. npt.inputmask.__valueSet = valueSet; //store native property setter
  2601. }
  2602. npt.inputmask._valueGet = function (overruleRTL) {
  2603. return isRTL && overruleRTL !== true ? valueGet.call(this.el).split("").reverse().join("") : valueGet.call(this.el);
  2604. };
  2605. npt.inputmask._valueSet = function (value, overruleRTL) { //null check is needed for IE8 => otherwise converts to "null"
  2606. valueSet.call(this.el, (value === null || value === undefined) ? "" : ((overruleRTL !== true && isRTL) ? value.split("").reverse().join("") : value));
  2607. };
  2608. if (valueGet === undefined) { //jquery.val fallback
  2609. valueGet = function () {
  2610. return this.value;
  2611. };
  2612. valueSet = function (value) {
  2613. this.value = value;
  2614. };
  2615. patchValhook(npt.type);
  2616. installNativeValueSetFallback(npt);
  2617. }
  2618. }
  2619. }
  2620. var elementType = input.getAttribute("type");
  2621. var isSupported = (input.tagName === "INPUT" && $.inArray(elementType, opts.supportsInputType) !== -1) || input.isContentEditable || input.tagName === "TEXTAREA";
  2622. if (!isSupported) {
  2623. if (input.tagName === "INPUT") {
  2624. var el = document.createElement("input");
  2625. el.setAttribute("type", elementType);
  2626. isSupported = el.type === "text"; //apply mask only if the type is not natively supported
  2627. el = null;
  2628. } else isSupported = "partial";
  2629. }
  2630. if (isSupported !== false) {
  2631. patchValueProperty(input);
  2632. }
  2633. return isSupported;
  2634. }
  2635. var isSupported = isElementTypeSupported(elem, opts);
  2636. if (isSupported !== false) {
  2637. el = elem;
  2638. $el = $(el);
  2639. if (el.dir === "rtl" || opts.rightAlign) {
  2640. el.style.textAlign = "right";
  2641. }
  2642. if (el.dir === "rtl" || opts.numericInput) {
  2643. el.dir = "ltr";
  2644. el.removeAttribute("dir");
  2645. el.inputmask.isRTL = true;
  2646. isRTL = true;
  2647. }
  2648. if (opts.colorMask === true) {
  2649. initializeColorMask(el);
  2650. }
  2651. if (android) {
  2652. if (el.hasOwnProperty("inputmode")) {
  2653. el.inputmode = opts.inputmode;
  2654. el.setAttribute("inputmode", opts.inputmode);
  2655. }
  2656. if (opts.androidHack === "rtfm") {
  2657. if (opts.colorMask !== true) {
  2658. initializeColorMask(el);
  2659. }
  2660. el.type = "password";
  2661. }
  2662. }
  2663. //unbind all events - to make sure that no other mask will interfere when re-masking
  2664. EventRuler.off(el);
  2665. if (isSupported === true) {
  2666. //bind events
  2667. EventRuler.on(el, "submit", EventHandlers.submitEvent);
  2668. EventRuler.on(el, "reset", EventHandlers.resetEvent);
  2669. EventRuler.on(el, "mouseenter", EventHandlers.mouseenterEvent);
  2670. EventRuler.on(el, "blur", EventHandlers.blurEvent);
  2671. EventRuler.on(el, "focus", EventHandlers.focusEvent);
  2672. EventRuler.on(el, "mouseleave", EventHandlers.mouseleaveEvent);
  2673. if (opts.colorMask !== true)
  2674. EventRuler.on(el, "click", EventHandlers.clickEvent);
  2675. EventRuler.on(el, "dblclick", EventHandlers.dblclickEvent);
  2676. EventRuler.on(el, "paste", EventHandlers.pasteEvent);
  2677. EventRuler.on(el, "dragdrop", EventHandlers.pasteEvent);
  2678. EventRuler.on(el, "drop", EventHandlers.pasteEvent);
  2679. EventRuler.on(el, "cut", EventHandlers.cutEvent);
  2680. EventRuler.on(el, "complete", opts.oncomplete);
  2681. EventRuler.on(el, "incomplete", opts.onincomplete);
  2682. EventRuler.on(el, "cleared", opts.oncleared);
  2683. if (opts.inputEventOnly !== true) {
  2684. EventRuler.on(el, "keydown", EventHandlers.keydownEvent);
  2685. EventRuler.on(el, "keypress", EventHandlers.keypressEvent);
  2686. }
  2687. EventRuler.on(el, "compositionstart", $.noop);
  2688. EventRuler.on(el, "compositionupdate", $.noop);
  2689. EventRuler.on(el, "compositionend", $.noop);
  2690. EventRuler.on(el, "keyup", $.noop);
  2691. EventRuler.on(el, "input", EventHandlers.inputFallBackEvent);
  2692. }
  2693. EventRuler.on(el, "setvalue", EventHandlers.setValueEvent);
  2694. //apply mask
  2695. getBufferTemplate(); //initialize the buffer and getmasklength
  2696. if (el.inputmask._valueGet() !== "" || opts.clearMaskOnLostFocus === false || document.activeElement === el) {
  2697. var initialValue = $.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(el.inputmask._valueGet(), opts) || el.inputmask._valueGet()) : el.inputmask._valueGet();
  2698. checkVal(el, true, false, initialValue.split(""));
  2699. var buffer = getBuffer().slice();
  2700. undoValue = buffer.join("");
  2701. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  2702. if (isComplete(buffer) === false) {
  2703. if (opts.clearIncomplete) {
  2704. resetMaskSet();
  2705. }
  2706. }
  2707. if (opts.clearMaskOnLostFocus && document.activeElement !== el) {
  2708. if (getLastValidPosition() === -1) {
  2709. buffer = [];
  2710. } else {
  2711. clearOptionalTail(buffer);
  2712. }
  2713. }
  2714. writeBuffer(el, buffer);
  2715. if (document.activeElement === el) { //position the caret when in focus
  2716. caret(el, seekNext(getLastValidPosition()));
  2717. }
  2718. }
  2719. }
  2720. }
  2721. //action object
  2722. var valueBuffer;
  2723. if (actionObj !== undefined) {
  2724. switch (actionObj.action) {
  2725. case "isComplete":
  2726. el = actionObj.el;
  2727. return isComplete(getBuffer());
  2728. case "unmaskedvalue":
  2729. if (el === undefined || actionObj.value !== undefined) {
  2730. valueBuffer = actionObj.value;
  2731. valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(valueBuffer, opts) || valueBuffer) : valueBuffer).split("");
  2732. checkVal(undefined, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  2733. if ($.isFunction(opts.onBeforeWrite)) opts.onBeforeWrite(undefined, getBuffer(), 0, opts);
  2734. }
  2735. return unmaskedvalue(el);
  2736. case "mask":
  2737. mask(el);
  2738. break;
  2739. case "format":
  2740. valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(actionObj.value, opts) || actionObj.value) : actionObj.value).split("");
  2741. checkVal(undefined, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  2742. if ($.isFunction(opts.onBeforeWrite)) opts.onBeforeWrite(undefined, getBuffer(), 0, opts);
  2743. if (actionObj.metadata) {
  2744. return {
  2745. value: isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join(""),
  2746. metadata: maskScope.call(this, {
  2747. "action": "getmetadata"
  2748. }, maskset, opts)
  2749. };
  2750. }
  2751. return isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join("");
  2752. case "isValid":
  2753. if (actionObj.value) {
  2754. valueBuffer = actionObj.value.split("");
  2755. checkVal(undefined, false, true, isRTL ? valueBuffer.reverse() : valueBuffer);
  2756. } else {
  2757. actionObj.value = getBuffer().join("");
  2758. }
  2759. var buffer = getBuffer();
  2760. var rl = determineLastRequiredPosition(),
  2761. lmib = buffer.length - 1;
  2762. for (; lmib > rl; lmib--) {
  2763. if (isMask(lmib)) break;
  2764. }
  2765. buffer.splice(rl, lmib + 1 - rl);
  2766. return isComplete(buffer) && actionObj.value === getBuffer().join("");
  2767. case "getemptymask":
  2768. return getBufferTemplate().join("");
  2769. case "remove":
  2770. if (el) {
  2771. $el = $(el);
  2772. //writeout the unmaskedvalue
  2773. el.inputmask._valueSet(unmaskedvalue(el));
  2774. //unbind all events
  2775. EventRuler.off(el);
  2776. //restore the value property
  2777. var valueProperty;
  2778. if (Object.getOwnPropertyDescriptor && Object.getPrototypeOf) {
  2779. valueProperty = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el), "value");
  2780. if (valueProperty) {
  2781. if (el.inputmask.__valueGet) {
  2782. Object.defineProperty(el, "value", {
  2783. get: el.inputmask.__valueGet,
  2784. set: el.inputmask.__valueSet,
  2785. configurable: true
  2786. });
  2787. }
  2788. }
  2789. } else if (document.__lookupGetter__ && el.__lookupGetter__("value")) {
  2790. if (el.inputmask.__valueGet) {
  2791. el.__defineGetter__("value", el.inputmask.__valueGet);
  2792. el.__defineSetter__("value", el.inputmask.__valueSet);
  2793. }
  2794. }
  2795. //clear data
  2796. el.inputmask = undefined;
  2797. }
  2798. return el;
  2799. break;
  2800. case "getmetadata":
  2801. if ($.isArray(maskset.metadata)) {
  2802. var maskTarget = getMaskTemplate(true, 0, false).join("");
  2803. $.each(maskset.metadata, function (ndx, mtdt) {
  2804. if (mtdt.mask === maskTarget) {
  2805. maskTarget = mtdt;
  2806. return false;
  2807. }
  2808. });
  2809. return maskTarget;
  2810. }
  2811. return maskset.metadata;
  2812. }
  2813. }
  2814. }
  2815. //make inputmask available
  2816. window.Inputmask = Inputmask;
  2817. return Inputmask;
  2818. }
  2819. ));