inputmask.js 170 KB

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