inputmask.js 168 KB

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