inputmask.js 177 KB

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