inputmask.js 178 KB

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