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