inputmask.js 169 KB

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