inputmask.js 178 KB

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