inputmask.js 173 KB

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