inputmask.js 115 KB

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