inputmask.js 186 KB

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