inputmask.js 114 KB

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