inputmask.js 180 KB

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