inputmask.js 115 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099
  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, isSelection, opts => return true/false/command object
  106. postValidation: null, //hook to postValidate the result from isValid. Usefull for validating the entry as a whole. args => buffer, currentResult, opts => return true/false/json
  107. staticDefinitionSymbol: undefined, //specify a definitionSymbol for static content, used to make matches for alternators
  108. jitMasking: false, //just in time masking ~ only mask while typing, can n (number), true or false
  109. nullable: true, //return nothing instead of the buffertemplate when the user hasn't entered anything.
  110. inputEventOnly: false, //dev option - testing inputfallback behavior
  111. noValuePatching: false, //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: function () {
  131. return true;
  132. },
  133. // validator: "[0-9A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]",
  134. cardinality: 1
  135. }
  136. },
  137. aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js
  138. masksCache: {},
  139. mask: function (elems) {
  140. var that = this;
  141. function importAttributeOptions(npt, opts, userOptions, dataAttribute) {
  142. var attrOptions = npt.getAttribute(dataAttribute),
  143. option, dataoptions, optionData, p;
  144. function importOption(option, optionData) {
  145. optionData = optionData !== undefined ? optionData : npt.getAttribute(dataAttribute + "-" + option);
  146. if (optionData !== null) {
  147. if (typeof optionData === "string") {
  148. if (option.indexOf("on") === 0) optionData = window[optionData]; //get function definition
  149. else if (optionData === "false") optionData = false;
  150. else if (optionData === "true") optionData = true;
  151. }
  152. userOptions[option] = optionData;
  153. }
  154. }
  155. if (attrOptions && attrOptions !== "") {
  156. attrOptions = attrOptions.replace(new RegExp("'", "g"), '"');
  157. dataoptions = JSON.parse("{" + attrOptions + "}");
  158. }
  159. //resolve aliases
  160. if (dataoptions) { //pickup alias from dataAttribute
  161. optionData = undefined;
  162. for (p in dataoptions) {
  163. if (p.toLowerCase() === "alias") {
  164. optionData = dataoptions[p];
  165. break;
  166. }
  167. }
  168. }
  169. importOption("alias", optionData); //pickup alias from dataAttribute-alias
  170. if (userOptions.alias) {
  171. resolveAlias(userOptions.alias, userOptions, opts);
  172. }
  173. for (option in opts) {
  174. if (dataoptions) {
  175. optionData = undefined;
  176. for (p in dataoptions) {
  177. if (p.toLowerCase() === option.toLowerCase()) {
  178. optionData = dataoptions[p];
  179. break;
  180. }
  181. }
  182. }
  183. importOption(option, optionData);
  184. }
  185. $.extend(true, opts, userOptions);
  186. return opts;
  187. }
  188. if (typeof elems === "string") {
  189. elems = document.getElementById(elems) || document.querySelectorAll(elems);
  190. }
  191. elems = elems.nodeName ? [elems] : elems;
  192. $.each(elems, function (ndx, el) {
  193. var scopedOpts = $.extend(true, {}, that.opts);
  194. importAttributeOptions(el, scopedOpts, $.extend(true, {}, that.userOptions), that.dataAttribute);
  195. var maskset = generateMaskSet(scopedOpts, that.noMasksCache);
  196. if (maskset !== undefined) {
  197. if (el.inputmask !== undefined) {
  198. el.inputmask.remove();
  199. }
  200. //store inputmask instance on the input with element reference
  201. el.inputmask = new Inputmask(undefined, undefined, true);
  202. el.inputmask.opts = scopedOpts;
  203. el.inputmask.noMasksCache = that.noMasksCache;
  204. el.inputmask.userOptions = $.extend(true, {}, that.userOptions);
  205. el.inputmask.isRTL = that.isRTL;
  206. el.inputmask.el = el;
  207. el.inputmask.maskset = maskset;
  208. $.data(el, "_inputmask_opts", scopedOpts);
  209. maskScope.call(el.inputmask, {
  210. "action": "mask"
  211. });
  212. }
  213. });
  214. return elems && elems[0] ? (elems[0].inputmask || this) : this;
  215. },
  216. option: function (options, noremask) { //set extra options || retrieve value of a current option
  217. if (typeof options === "string") {
  218. return this.opts[options];
  219. } else if (typeof options === "object") {
  220. $.extend(this.userOptions, options); //user passed options
  221. //remask
  222. if (this.el && noremask !== true) {
  223. this.mask(this.el);
  224. }
  225. return this;
  226. }
  227. },
  228. unmaskedvalue: function (value) {
  229. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  230. return maskScope.call(this, {
  231. "action": "unmaskedvalue",
  232. "value": value
  233. });
  234. },
  235. remove: function () {
  236. return maskScope.call(this, {
  237. "action": "remove"
  238. });
  239. },
  240. getemptymask: function () { //return the default (empty) mask value, usefull for setting the default value in validation
  241. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  242. return maskScope.call(this, {
  243. "action": "getemptymask"
  244. });
  245. },
  246. hasMaskedValue: function () { //check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value
  247. return !this.opts.autoUnmask;
  248. },
  249. isComplete: function () {
  250. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  251. return maskScope.call(this, {
  252. "action": "isComplete"
  253. });
  254. },
  255. getmetadata: function () { //return mask metadata if exists
  256. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  257. return maskScope.call(this, {
  258. "action": "getmetadata"
  259. });
  260. },
  261. isValid: function (value) {
  262. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  263. return maskScope.call(this, {
  264. "action": "isValid",
  265. "value": value
  266. });
  267. },
  268. format: function (value, metadata) {
  269. this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
  270. return maskScope.call(this, {
  271. "action": "format",
  272. "value": value,
  273. "metadata": metadata //true/false getmetadata
  274. });
  275. },
  276. analyseMask: function (mask, opts) {
  277. var tokenizer = /(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?\})|[^.?*+^${[]()|\\]+|./g,
  278. escaped = false,
  279. currentToken = new MaskToken(),
  280. match,
  281. m,
  282. openenings = [],
  283. maskTokens = [],
  284. openingToken,
  285. currentOpeningToken,
  286. alternator,
  287. lastMatch,
  288. groupToken;
  289. function MaskToken(isGroup, isOptional, isQuantifier, isAlternator) {
  290. this.matches = [];
  291. this.openGroup = isGroup || false;
  292. this.isGroup = isGroup || false;
  293. this.isOptional = isOptional || false;
  294. this.isQuantifier = isQuantifier || false;
  295. this.isAlternator = isAlternator || false;
  296. this.quantifier = {
  297. min: 1,
  298. max: 1
  299. };
  300. }
  301. //test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, casing: null/upper/lower, def: definitionSymbol, placeholder: placeholder, mask: real maskDefinition}
  302. function insertTestDefinition(mtoken, element, position) {
  303. var maskdef = (opts.definitions ? opts.definitions[element] : undefined) || Inputmask.prototype.definitions[element];
  304. position = position !== undefined ? position : mtoken.matches.length;
  305. var prevMatch = mtoken.matches[position - 1];
  306. if (maskdef && !escaped) {
  307. var prevalidators = maskdef.prevalidator,
  308. prevalidatorsL = prevalidators ? prevalidators.length : 0;
  309. //handle prevalidators
  310. for (var i = 1; i < maskdef.cardinality; i++) {
  311. var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [],
  312. validator = prevalidator.validator,
  313. cardinality = prevalidator.cardinality;
  314. mtoken.matches.splice(position++, 0, {
  315. fn: validator ? typeof validator === "string" ? new RegExp(validator) : new function () {
  316. this.test = validator;
  317. } : new RegExp("."),
  318. cardinality: cardinality ? cardinality : 1,
  319. optionality: mtoken.isOptional,
  320. newBlockMarker: prevMatch === undefined || prevMatch.def !== (maskdef.definitionSymbol || element),
  321. casing: maskdef.casing,
  322. def: maskdef.definitionSymbol || element,
  323. placeholder: maskdef.placeholder,
  324. nativeDef: element
  325. });
  326. prevMatch = mtoken.matches[position - 1];
  327. }
  328. mtoken.matches.splice(position++, 0, {
  329. fn: maskdef.validator ? typeof maskdef.validator == "string" ? new RegExp(maskdef.validator) : new function () {
  330. this.test = maskdef.validator;
  331. } : new RegExp("."),
  332. cardinality: maskdef.cardinality,
  333. optionality: mtoken.isOptional,
  334. newBlockMarker: prevMatch === undefined || prevMatch.def !== (maskdef.definitionSymbol || element),
  335. casing: maskdef.casing,
  336. def: maskdef.definitionSymbol || element,
  337. placeholder: maskdef.placeholder,
  338. nativeDef: element
  339. });
  340. } else {
  341. mtoken.matches.splice(position++, 0, {
  342. fn: null,
  343. cardinality: 0,
  344. optionality: mtoken.isOptional,
  345. newBlockMarker: prevMatch === undefined || prevMatch.def !== element,
  346. casing: null,
  347. def: opts.staticDefinitionSymbol || element,
  348. placeholder: opts.staticDefinitionSymbol !== undefined ? element : undefined,
  349. nativeDef: element
  350. });
  351. escaped = false;
  352. }
  353. }
  354. function verifyGroupMarker(maskToken) {
  355. if (maskToken && maskToken.matches) {
  356. $.each(maskToken.matches, function (ndx, token) {
  357. var nextToken = maskToken.matches[ndx + 1];
  358. if ((nextToken === undefined || (nextToken.matches === undefined || nextToken.isQuantifier === false)) && token && token.isGroup) { //this is not a group but a normal mask => convert
  359. token.isGroup = false;
  360. insertTestDefinition(token, opts.groupmarker.start, 0);
  361. if (token.openGroup !== true) {
  362. insertTestDefinition(token, opts.groupmarker.end);
  363. }
  364. }
  365. verifyGroupMarker(token);
  366. }
  367. );
  368. }
  369. }
  370. function defaultCase() {
  371. if (openenings.length > 0) {
  372. currentOpeningToken = openenings[openenings.length - 1];
  373. insertTestDefinition(currentOpeningToken, m);
  374. if (currentOpeningToken.isAlternator) { //handle alternator a | b case
  375. alternator = openenings.pop();
  376. for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
  377. alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group
  378. }
  379. if (openenings.length > 0) {
  380. currentOpeningToken = openenings[openenings.length - 1];
  381. currentOpeningToken.matches.push(alternator);
  382. } else {
  383. currentToken.matches.push(alternator);
  384. }
  385. }
  386. } else {
  387. insertTestDefinition(currentToken, m);
  388. }
  389. }
  390. function reverseTokens(maskToken) {
  391. function reverseStatic(st) {
  392. if (st === opts.optionalmarker.start) st = opts.optionalmarker.end;
  393. else if (st === opts.optionalmarker.end) st = opts.optionalmarker.start;
  394. else if (st === opts.groupmarker.start) st = opts.groupmarker.end;
  395. else if (st === opts.groupmarker.end) st = opts.groupmarker.start;
  396. return st;
  397. }
  398. maskToken.matches = maskToken.matches.reverse();
  399. for (var match in maskToken.matches) {
  400. if (maskToken.matches.hasOwnProperty(match)) {
  401. var intMatch = parseInt(match);
  402. if (maskToken.matches[match].isQuantifier && maskToken.matches[intMatch + 1] && maskToken.matches[intMatch + 1].isGroup) { //reposition quantifier
  403. var qt = maskToken.matches[match];
  404. maskToken.matches.splice(match, 1);
  405. maskToken.matches.splice(intMatch + 1, 0, qt);
  406. }
  407. if (maskToken.matches[match].matches !== undefined) {
  408. maskToken.matches[match] = reverseTokens(maskToken.matches[match]);
  409. } else {
  410. maskToken.matches[match] = reverseStatic(maskToken.matches[match]);
  411. }
  412. }
  413. }
  414. return maskToken;
  415. }
  416. while (match = tokenizer.exec(mask)) {
  417. m = match[0];
  418. if (escaped) {
  419. defaultCase();
  420. continue;
  421. }
  422. switch (m.charAt(0)) {
  423. case opts.escapeChar:
  424. escaped = true;
  425. break;
  426. case opts.optionalmarker.end:
  427. // optional closing
  428. case opts.groupmarker.end:
  429. // Group closing
  430. openingToken = openenings.pop();
  431. openingToken.openGroup = false; //mark group as complete
  432. if (openingToken !== undefined) {
  433. if (openenings.length > 0) {
  434. currentOpeningToken = openenings[openenings.length - 1];
  435. currentOpeningToken.matches.push(openingToken);
  436. if (currentOpeningToken.isAlternator) { //handle alternator (a) | (b) case
  437. alternator = openenings.pop();
  438. for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
  439. alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group
  440. }
  441. if (openenings.length > 0) {
  442. currentOpeningToken = openenings[openenings.length - 1];
  443. currentOpeningToken.matches.push(alternator);
  444. } else {
  445. currentToken.matches.push(alternator);
  446. }
  447. }
  448. } else {
  449. currentToken.matches.push(openingToken);
  450. }
  451. } else defaultCase();
  452. break;
  453. case opts.optionalmarker.start:
  454. // optional opening
  455. openenings.push(new MaskToken(false, true));
  456. break;
  457. case opts.groupmarker.start:
  458. // Group opening
  459. openenings.push(new MaskToken(true));
  460. break;
  461. case opts.quantifiermarker.start:
  462. //Quantifier
  463. var quantifier = new MaskToken(false, false, true);
  464. m = m.replace(/[{}]/g, "");
  465. var mq = m.split(","),
  466. mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]),
  467. mq1 = mq.length === 1 ? mq0 : (isNaN(mq[1]) ? mq[1] : parseInt(mq[1]));
  468. if (mq1 === "*" || mq1 === "+") {
  469. mq0 = mq1 === "*" ? 0 : 1;
  470. }
  471. quantifier.quantifier = {
  472. min: mq0,
  473. max: mq1
  474. };
  475. if (openenings.length > 0) {
  476. var matches = openenings[openenings.length - 1].matches;
  477. match = matches.pop();
  478. if (!match.isGroup) {
  479. groupToken = new MaskToken(true);
  480. groupToken.matches.push(match);
  481. match = groupToken;
  482. }
  483. matches.push(match);
  484. matches.push(quantifier);
  485. } else {
  486. match = currentToken.matches.pop();
  487. if (!match.isGroup) {
  488. groupToken = new MaskToken(true);
  489. groupToken.matches.push(match);
  490. match = groupToken;
  491. }
  492. currentToken.matches.push(match);
  493. currentToken.matches.push(quantifier);
  494. }
  495. break;
  496. case
  497. opts.alternatormarker:
  498. if (openenings.length > 0) {
  499. currentOpeningToken = openenings[openenings.length - 1];
  500. lastMatch = currentOpeningToken.matches.pop();
  501. } else {
  502. lastMatch = currentToken.matches.pop();
  503. }
  504. if (lastMatch.isAlternator) {
  505. openenings.push(lastMatch);
  506. } else {
  507. alternator = new MaskToken(false, false, false, true);
  508. alternator.matches.push(lastMatch);
  509. openenings.push(alternator);
  510. }
  511. break;
  512. default:
  513. defaultCase();
  514. }
  515. }
  516. while (openenings.length > 0) {
  517. openingToken = openenings.pop();
  518. currentToken.matches.push(openingToken);
  519. }
  520. if (currentToken.matches.length > 0) {
  521. verifyGroupMarker(currentToken);
  522. maskTokens.push(currentToken);
  523. }
  524. if (opts.numericInput) {
  525. reverseTokens(maskTokens[0]);
  526. }
  527. // console.log(JSON.stringify(maskTokens));
  528. return maskTokens;
  529. }
  530. };
  531. //apply defaults, definitions, aliases
  532. Inputmask.extendDefaults = function (options) {
  533. $.extend(true, Inputmask.prototype.defaults, options);
  534. };
  535. Inputmask.extendDefinitions = function (definition) {
  536. $.extend(true, Inputmask.prototype.definitions, definition);
  537. };
  538. Inputmask.extendAliases = function (alias) {
  539. $.extend(true, Inputmask.prototype.aliases, alias);
  540. };
  541. //static fn on inputmask
  542. Inputmask.format = function (value, options, metadata) {
  543. return Inputmask(options).format(value, metadata);
  544. };
  545. Inputmask.unmask = function (value, options) {
  546. return Inputmask(options).unmaskedvalue(value);
  547. };
  548. Inputmask.isValid = function (value, options) {
  549. return Inputmask(options).isValid(value);
  550. };
  551. Inputmask.remove = function (elems) {
  552. $.each(elems, function (ndx, el) {
  553. if (el.inputmask) el.inputmask.remove();
  554. });
  555. };
  556. Inputmask.escapeRegex = function (str) {
  557. var specials = ["/", ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\", "$", "^"];
  558. return str.replace(new RegExp("(\\" + specials.join("|\\") + ")", "gim"), "\\$1");
  559. };
  560. Inputmask.keyCode = {
  561. ALT: 18,
  562. BACKSPACE: 8,
  563. BACKSPACE_SAFARI: 127,
  564. CAPS_LOCK: 20,
  565. COMMA: 188,
  566. COMMAND: 91,
  567. COMMAND_LEFT: 91,
  568. COMMAND_RIGHT: 93,
  569. CONTROL: 17,
  570. DELETE: 46,
  571. DOWN: 40,
  572. END: 35,
  573. ENTER: 13,
  574. ESCAPE: 27,
  575. HOME: 36,
  576. INSERT: 45,
  577. LEFT: 37,
  578. MENU: 93,
  579. NUMPAD_ADD: 107,
  580. NUMPAD_DECIMAL: 110,
  581. NUMPAD_DIVIDE: 111,
  582. NUMPAD_ENTER: 108,
  583. NUMPAD_MULTIPLY: 106,
  584. NUMPAD_SUBTRACT: 109,
  585. PAGE_DOWN: 34,
  586. PAGE_UP: 33,
  587. PERIOD: 190,
  588. RIGHT: 39,
  589. SHIFT: 16,
  590. SPACE: 32,
  591. TAB: 9,
  592. UP: 38,
  593. WINDOWS: 91,
  594. X: 88
  595. };
  596. function resolveAlias(aliasStr, options, opts) {
  597. var aliasDefinition = Inputmask.prototype.aliases[aliasStr];
  598. if (aliasDefinition) {
  599. if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias, undefined, opts); //alias is another alias
  600. $.extend(true, opts, aliasDefinition); //merge alias definition in the options
  601. $.extend(true, opts, options); //reapply extra given options
  602. return true;
  603. } else //alias not found - try as mask
  604. if (opts.mask === null) {
  605. opts.mask = aliasStr;
  606. }
  607. return false;
  608. }
  609. function generateMaskSet(opts, nocache) {
  610. function generateMask(mask, metadata, opts) {
  611. if (mask === null || mask === "") {
  612. mask = "*{*}";
  613. }
  614. if (mask.length === 1 && opts.greedy === false && opts.repeat !== 0) {
  615. opts.placeholder = "";
  616. } //hide placeholder with single non-greedy mask
  617. if (opts.repeat > 0 || opts.repeat === "*" || opts.repeat === "+") {
  618. var repeatStart = opts.repeat === "*" ? 0 : (opts.repeat === "+" ? 1 : opts.repeat);
  619. mask = opts.groupmarker.start + mask + opts.groupmarker.end + opts.quantifiermarker.start + repeatStart + "," + opts.repeat + opts.quantifiermarker.end;
  620. }
  621. // console.log(mask);
  622. var masksetDefinition;
  623. if (Inputmask.prototype.masksCache[mask] === undefined || nocache === true) {
  624. masksetDefinition = {
  625. "mask": mask,
  626. "maskToken": Inputmask.prototype.analyseMask(mask, opts),
  627. "validPositions": {},
  628. "_buffer": undefined,
  629. "buffer": undefined,
  630. "tests": {},
  631. "metadata": metadata,
  632. maskLength: undefined
  633. };
  634. if (nocache !== true) {
  635. Inputmask.prototype.masksCache[opts.numericInput ? mask.split("").reverse().join("") : mask] = masksetDefinition;
  636. masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[opts.numericInput ? mask.split("").reverse().join("") : mask]);
  637. }
  638. } else masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[opts.numericInput ? mask.split("").reverse().join("") : mask]);
  639. return masksetDefinition;
  640. }
  641. var ms;
  642. if ($.isFunction(opts.mask)) { //allow mask to be a preprocessing fn - should return a valid mask
  643. opts.mask = opts.mask(opts);
  644. }
  645. if ($.isArray(opts.mask)) {
  646. if (opts.mask.length > 1) {
  647. opts.keepStatic = opts.keepStatic === null ? true : opts.keepStatic; //enable by default when passing multiple masks when the option is not explicitly specified
  648. var altMask = opts.groupmarker.start;
  649. $.each(opts.numericInput ? opts.mask.reverse() : opts.mask, function (ndx, msk) {
  650. if (altMask.length > 1) {
  651. altMask += opts.groupmarker.end + opts.alternatormarker + opts.groupmarker.start;
  652. }
  653. if (msk.mask !== undefined && !$.isFunction(msk.mask)) {
  654. altMask += msk.mask;
  655. } else {
  656. altMask += msk;
  657. }
  658. });
  659. altMask += opts.groupmarker.end;
  660. // console.log(altMask);
  661. return generateMask(altMask, opts.mask, opts);
  662. } else opts.mask = opts.mask.pop();
  663. }
  664. if (opts.mask && opts.mask.mask !== undefined && !$.isFunction(opts.mask.mask)) {
  665. ms = generateMask(opts.mask.mask, opts.mask, opts);
  666. } else {
  667. ms = generateMask(opts.mask, opts.mask, opts);
  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 = 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) :
  1201. (posObj.end - posObj.begin) > 1 || ((posObj.end - posObj.begin) === 1);
  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(), maskPos, c, isSelection(pos), 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 = getTestTemplate(pos).match;
  1559. if (test.def === "") test = getTest(pos).match;
  1560. if (test.fn != null) {
  1561. return test.fn;
  1562. } else if (strict !== true && pos > -1) {
  1563. var tests = getTests(pos);
  1564. return tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0);
  1565. }
  1566. return false;
  1567. }
  1568. function seekNext(pos, newBlock) {
  1569. var maskL = getMaskSet().maskLength;
  1570. if (pos >= maskL) return maskL;
  1571. var position = pos;
  1572. while (++position < maskL &&
  1573. ((newBlock === true && (getTest(position).match.newBlockMarker !== true || !isMask(position))) ||
  1574. (newBlock !== true && !isMask(position)))) {
  1575. }
  1576. return position;
  1577. }
  1578. function seekPrevious(pos, newBlock) {
  1579. var position = pos, tests;
  1580. if (position <= 0) return 0;
  1581. while (--position > 0 &&
  1582. ((newBlock === true && getTest(position).match.newBlockMarker !== true) ||
  1583. (newBlock !== true && !isMask(position) &&
  1584. (tests = getTests(position), tests.length < 2 || (tests.length === 2 && tests[1].match.def === ""))))) {
  1585. }
  1586. return position;
  1587. }
  1588. function getBufferElement(position) {
  1589. return getMaskSet().validPositions[position] === undefined ? getPlaceholder(position) : getMaskSet().validPositions[position].input;
  1590. }
  1591. function writeBuffer(input, buffer, caretPos, event, triggerInputEvent) {
  1592. if (event && $.isFunction(opts.onBeforeWrite)) {
  1593. var result = opts.onBeforeWrite(event, buffer, caretPos, opts);
  1594. if (result) {
  1595. if (result.refreshFromBuffer) {
  1596. var refresh = result.refreshFromBuffer;
  1597. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer || buffer);
  1598. buffer = getBuffer(true);
  1599. }
  1600. //only alter when intented !== undefined
  1601. if (caretPos !== undefined) caretPos = result.caret !== undefined ? result.caret : caretPos;
  1602. }
  1603. }
  1604. if (input !== undefined) {
  1605. input.inputmask._valueSet(buffer.join(""));
  1606. if (caretPos !== undefined && (event === undefined || event.type !== "blur")) {
  1607. if (android && event.type === "input") {
  1608. setTimeout(function () {
  1609. caret(input, caretPos);
  1610. }, 0);
  1611. } else caret(input, caretPos);
  1612. } else renderColorMask(input, buffer, caretPos);
  1613. if (triggerInputEvent === true) {
  1614. skipInputEvent = true;
  1615. $(input).trigger("input");
  1616. }
  1617. }
  1618. }
  1619. function getPlaceholder(pos, test, returnPL) {
  1620. test = test || getTest(pos).match;
  1621. if (test.placeholder !== undefined || returnPL === true) {
  1622. return $.isFunction(test.placeholder) ? test.placeholder(opts) : test.placeholder;
  1623. } else if (test.fn === null) {
  1624. if (pos > -1 && getMaskSet().validPositions[pos] === undefined) {
  1625. var tests = getTests(pos),
  1626. staticAlternations = [],
  1627. prevTest;
  1628. if (tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0)) {
  1629. for (var i = 0; i < tests.length; i++) {
  1630. if (tests[i].match.optionality !== true && tests[i].match.optionalQuantifier !== true &&
  1631. (tests[i].match.fn === null || (prevTest === undefined || tests[i].match.fn.test(prevTest.match.def, getMaskSet(), pos, true, opts) !== false))) {
  1632. staticAlternations.push(tests[i]);
  1633. if (tests[i].match.fn === null) prevTest = tests[i];
  1634. if (staticAlternations.length > 1) {
  1635. if (/[0-9a-bA-Z]/.test(staticAlternations[0].match.def)) {
  1636. return opts.placeholder.charAt(pos % opts.placeholder.length);
  1637. }
  1638. }
  1639. }
  1640. }
  1641. }
  1642. }
  1643. return test.def;
  1644. }
  1645. return opts.placeholder.charAt(pos % opts.placeholder.length);
  1646. }
  1647. function checkVal(input, writeOut, strict, nptvl, initiatingEvent) {
  1648. var inputValue = nptvl.slice(),
  1649. charCodes = "",
  1650. initialNdx = 0, result = undefined;
  1651. // console.log(nptvl);
  1652. function isTemplateMatch(ndx, charCodes) {
  1653. var charCodeNdx = getBufferTemplate().slice(ndx, seekNext(ndx)).join("").indexOf(charCodes);
  1654. return charCodeNdx !== -1 && !isMask(ndx) && getTest(ndx).match.nativeDef === charCodes.charAt(charCodes.length - 1);
  1655. }
  1656. resetMaskSet();
  1657. getMaskSet().p = seekNext(-1);
  1658. // if (writeOut) input.inputmask._valueSet(""); //initial clear
  1659. if (!strict) {
  1660. if (opts.autoUnmask !== true) {
  1661. var staticInput = getBufferTemplate().slice(0, seekNext(-1)).join(""),
  1662. matches = inputValue.join("").match(new RegExp("^" + Inputmask.escapeRegex(staticInput), "g"));
  1663. if (matches && matches.length > 0) {
  1664. inputValue.splice(0, matches.length * staticInput.length);
  1665. initialNdx = seekNext(initialNdx);
  1666. }
  1667. } else {
  1668. initialNdx = seekNext(initialNdx);
  1669. }
  1670. }
  1671. $.each(inputValue, function (ndx, charCode) {
  1672. if (charCode !== undefined) { //inputfallback strips some elements out of the inputarray. $.each logically presents them as undefined
  1673. var keypress = new $.Event("_checkval");
  1674. keypress.which = charCode.charCodeAt(0);
  1675. charCodes += charCode;
  1676. var lvp = getLastValidPosition(undefined, true),
  1677. lvTest = getMaskSet().validPositions[lvp],
  1678. nextTest = getTestTemplate(lvp + 1, lvTest ? lvTest.locator.slice() : undefined, lvp);
  1679. if (!isTemplateMatch(initialNdx, charCodes) || strict || opts.autoUnmask) {
  1680. var pos = strict ? ndx : (nextTest.match.fn == null && nextTest.match.optionality && (lvp + 1) < getMaskSet().p ? lvp + 1 : getMaskSet().p);
  1681. result = EventHandlers.keypressEvent.call(input, keypress, true, false, strict, pos);
  1682. initialNdx = pos + 1;
  1683. charCodes = "";
  1684. } else {
  1685. result = EventHandlers.keypressEvent.call(input, keypress, true, false, true, lvp + 1);
  1686. }
  1687. if (!strict && $.isFunction(opts.onBeforeWrite)) {
  1688. var fp = result.forwardPosition;
  1689. result = opts.onBeforeWrite(keypress, getBuffer(), result.forwardPosition, opts);
  1690. result.forwardPosition = fp;
  1691. if (result && result.refreshFromBuffer) {
  1692. var refresh = result.refreshFromBuffer;
  1693. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer);
  1694. resetMaskSet(true);
  1695. if (result.caret) {
  1696. getMaskSet().p = result.caret;
  1697. result.forwardPosition = result.caret;
  1698. }
  1699. }
  1700. }
  1701. }
  1702. });
  1703. if (writeOut) {
  1704. var caretPos = undefined;
  1705. if (document.activeElement === input && result) {
  1706. caretPos = opts.numericInput ? seekPrevious(result.forwardPosition) : result.forwardPosition;
  1707. }
  1708. writeBuffer(input, getBuffer(), caretPos, initiatingEvent || new $.Event("checkval"));
  1709. }
  1710. }
  1711. function unmaskedvalue(input) {
  1712. if (input) {
  1713. if (input.inputmask === undefined) {
  1714. return input.value;
  1715. }
  1716. if (input.inputmask && input.inputmask.refreshValue) { //forced refresh from the value form.reset
  1717. EventHandlers.setValueEvent.call(input);
  1718. }
  1719. }
  1720. var umValue = [],
  1721. vps = getMaskSet().validPositions;
  1722. for (var pndx in vps) {
  1723. if (vps[pndx].match && vps[pndx].match.fn != null) {
  1724. umValue.push(vps[pndx].input);
  1725. }
  1726. }
  1727. var unmaskedValue = umValue.length === 0 ? "" : (isRTL ? umValue.reverse() : umValue).join("");
  1728. if ($.isFunction(opts.onUnMask)) {
  1729. var bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join("");
  1730. unmaskedValue = opts.onUnMask(bufferValue, unmaskedValue, opts);
  1731. }
  1732. return unmaskedValue;
  1733. }
  1734. function caret(input, begin, end, notranslate) {
  1735. function translatePosition(pos) {
  1736. if (notranslate !== true && isRTL && typeof pos === "number" && (!opts.greedy || opts.placeholder !== "")) {
  1737. 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)
  1738. pos = bffrLght - pos;
  1739. }
  1740. return pos;
  1741. }
  1742. var range;
  1743. if (typeof begin === "number") {
  1744. begin = translatePosition(begin);
  1745. end = translatePosition(end);
  1746. end = (typeof end == "number") ? end : begin;
  1747. // if (!$(input).is(":visible")) {
  1748. // return;
  1749. // }
  1750. var scrollCalc = parseInt(((input.ownerDocument.defaultView || window).getComputedStyle ? (input.ownerDocument.defaultView || window).getComputedStyle(input, null) : input.currentStyle).fontSize) * end;
  1751. input.scrollLeft = scrollCalc > input.scrollWidth ? scrollCalc : 0;
  1752. if (!mobile && opts.insertMode === false && begin === end) end++; //set visualization for insert/overwrite mode
  1753. if (input.setSelectionRange) {
  1754. input.selectionStart = begin;
  1755. input.selectionEnd = end;
  1756. } else if (window.getSelection) {
  1757. range = document.createRange();
  1758. if (input.firstChild === undefined || input.firstChild === null) {
  1759. var textNode = document.createTextNode("");
  1760. input.appendChild(textNode);
  1761. }
  1762. range.setStart(input.firstChild, begin < input.inputmask._valueGet().length ? begin : input.inputmask._valueGet().length);
  1763. range.setEnd(input.firstChild, end < input.inputmask._valueGet().length ? end : input.inputmask._valueGet().length);
  1764. range.collapse(true);
  1765. var sel = window.getSelection();
  1766. sel.removeAllRanges();
  1767. sel.addRange(range);
  1768. //input.focus();
  1769. } else if (input.createTextRange) {
  1770. range = input.createTextRange();
  1771. range.collapse(true);
  1772. range.moveEnd("character", end);
  1773. range.moveStart("character", begin);
  1774. range.select();
  1775. }
  1776. renderColorMask(input, undefined, {begin: begin, end: end});
  1777. } else {
  1778. if (input.setSelectionRange) {
  1779. begin = input.selectionStart;
  1780. end = input.selectionEnd;
  1781. } else if (window.getSelection) {
  1782. range = window.getSelection().getRangeAt(0);
  1783. if (range.commonAncestorContainer.parentNode === input || range.commonAncestorContainer === input) {
  1784. begin = range.startOffset;
  1785. end = range.endOffset;
  1786. }
  1787. } else if (document.selection && document.selection.createRange) {
  1788. range = document.selection.createRange();
  1789. begin = 0 - range.duplicate().moveStart("character", -input.inputmask._valueGet().length);
  1790. end = begin + range.text.length;
  1791. }
  1792. /*eslint-disable consistent-return */
  1793. return {
  1794. "begin": translatePosition(begin),
  1795. "end": translatePosition(end)
  1796. };
  1797. /*eslint-enable consistent-return */
  1798. }
  1799. }
  1800. function determineLastRequiredPosition(returnDefinition) {
  1801. var buffer = getBuffer(),
  1802. bl = buffer.length,
  1803. pos, lvp = getLastValidPosition(),
  1804. positions = {},
  1805. lvTest = getMaskSet().validPositions[lvp],
  1806. ndxIntlzr = lvTest !== undefined ? lvTest.locator.slice() : undefined,
  1807. testPos;
  1808. for (pos = lvp + 1; pos < buffer.length; pos++) {
  1809. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  1810. ndxIntlzr = testPos.locator.slice();
  1811. positions[pos] = $.extend(true, {}, testPos);
  1812. }
  1813. var lvTestAlt = lvTest && lvTest.alternation !== undefined ? lvTest.locator[lvTest.alternation] : undefined;
  1814. for (pos = bl - 1; pos > lvp; pos--) {
  1815. testPos = positions[pos];
  1816. if ((testPos.match.optionality ||
  1817. testPos.match.optionalQuantifier ||
  1818. (lvTestAlt &&
  1819. ((lvTestAlt !== positions[pos].locator[lvTest.alternation] && testPos.match.fn != null) ||
  1820. (testPos.match.fn === null && testPos.locator[lvTest.alternation] && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAlt.toString().split(",")) && getTests(pos)[0].def !== "")))) &&
  1821. buffer[pos] === getPlaceholder(pos, testPos.match)) {
  1822. bl--;
  1823. } else break;
  1824. }
  1825. return returnDefinition ? {
  1826. "l": bl,
  1827. "def": positions[bl] ? positions[bl].match : undefined
  1828. } : bl;
  1829. }
  1830. function clearOptionalTail(buffer) {
  1831. var rl = determineLastRequiredPosition(),
  1832. validPos, bl = buffer.length;
  1833. while (rl < bl && !isMask(rl + 1) && (validPos = getTest(rl + 1)) && validPos.match.optionality !== true && validPos.match.optionalQuantifier !== true) {
  1834. rl++;
  1835. }
  1836. while ((validPos = getTest(rl - 1)) && validPos.match.optionality && validPos.input === opts.skipOptionalPartCharacter) {
  1837. rl--;
  1838. }
  1839. buffer.splice(rl);
  1840. return buffer;
  1841. }
  1842. function isComplete(buffer) { //return true / false / undefined (repeat *)
  1843. if ($.isFunction(opts.isComplete)) return opts.isComplete(buffer, opts);
  1844. if (opts.repeat === "*") return undefined;
  1845. var complete = false,
  1846. lrp = determineLastRequiredPosition(true),
  1847. aml = seekPrevious(lrp.l);
  1848. if (lrp.def === undefined || lrp.def.newBlockMarker || lrp.def.optionality || lrp.def.optionalQuantifier) {
  1849. complete = true;
  1850. for (var i = 0; i <= aml; i++) {
  1851. var test = getTestTemplate(i).match;
  1852. if ((test.fn !== null && getMaskSet().validPositions[i] === undefined && test.optionality !== true && test.optionalQuantifier !== true) || (test.fn === null && buffer[i] !== getPlaceholder(i, test))) {
  1853. complete = false;
  1854. break;
  1855. }
  1856. }
  1857. }
  1858. return complete;
  1859. }
  1860. function handleRemove(input, k, pos, strict) {
  1861. function generalize() {
  1862. if (opts.keepStatic) {
  1863. var validInputs = [],
  1864. lastAlt = getLastValidPosition(-1, true), positionsClone = $.extend(true, {}, getMaskSet().validPositions),
  1865. prevAltPos = getMaskSet().validPositions[lastAlt];
  1866. //find last alternation
  1867. for (; lastAlt >= 0; lastAlt--) {
  1868. var altPos = getMaskSet().validPositions[lastAlt];
  1869. if (altPos) {
  1870. if (altPos.generatedInput !== true && /[0-9a-bA-Z]/.test(altPos.input)) {
  1871. validInputs.push(altPos.input);
  1872. }
  1873. delete getMaskSet().validPositions[lastAlt];
  1874. if (altPos.alternation !== undefined && altPos.locator[altPos.alternation] !== prevAltPos.locator[altPos.alternation]) {
  1875. break;
  1876. }
  1877. prevAltPos = altPos;
  1878. }
  1879. }
  1880. if (lastAlt > -1) {
  1881. getMaskSet().p = seekNext(getLastValidPosition(-1, true));
  1882. while (validInputs.length > 0) {
  1883. var keypress = new $.Event("keypress");
  1884. keypress.which = validInputs.pop().charCodeAt(0);
  1885. EventHandlers.keypressEvent.call(input, keypress, true, false, false, getMaskSet().p);
  1886. }
  1887. } else getMaskSet().validPositions = $.extend(true, {}, positionsClone); //restore original positions
  1888. }
  1889. }
  1890. if (opts.numericInput || isRTL) {
  1891. if (k === Inputmask.keyCode.BACKSPACE) {
  1892. k = Inputmask.keyCode.DELETE;
  1893. } else if (k === Inputmask.keyCode.DELETE) {
  1894. k = Inputmask.keyCode.BACKSPACE;
  1895. }
  1896. if (isRTL) {
  1897. var pend = pos.end;
  1898. pos.end = pos.begin;
  1899. pos.begin = pend;
  1900. }
  1901. }
  1902. if (k === Inputmask.keyCode.BACKSPACE && (pos.end - pos.begin < 1 || opts.insertMode === false)) {
  1903. pos.begin = seekPrevious(pos.begin);
  1904. if (getMaskSet().validPositions[pos.begin] !== undefined && (getMaskSet().validPositions[pos.begin].input === opts.groupSeparator || getMaskSet().validPositions[pos.begin].input === opts.radixPoint)) {
  1905. pos.begin--;
  1906. }
  1907. } else if (k === Inputmask.keyCode.DELETE && pos.begin === pos.end) {
  1908. pos.end = isMask(pos.end, true) ? pos.end + 1 : seekNext(pos.end) + 1;
  1909. if (getMaskSet().validPositions[pos.begin] !== undefined && (getMaskSet().validPositions[pos.begin].input === opts.groupSeparator || getMaskSet().validPositions[pos.begin].input === opts.radixPoint)) {
  1910. pos.end++;
  1911. }
  1912. }
  1913. stripValidPositions(pos.begin, pos.end, false, strict);
  1914. if (strict !== true) {
  1915. generalize(); //revert the alternation
  1916. }
  1917. var lvp = getLastValidPosition(pos.begin, true);
  1918. if (lvp < pos.begin) {
  1919. //if (lvp === -1) resetMaskSet();
  1920. getMaskSet().p = seekNext(lvp);
  1921. } else if (strict !== true) {
  1922. getMaskSet().p = pos.begin;
  1923. }
  1924. }
  1925. var EventRuler = {
  1926. on: function (input, eventName, eventHandler) {
  1927. var ev = function (e) {
  1928. // console.log("triggered " + e.type);
  1929. if (this.inputmask === undefined && this.nodeName !== "FORM") { //happens when cloning an object with jquery.clone
  1930. var imOpts = $.data(this, "_inputmask_opts");
  1931. if (imOpts) (new Inputmask(imOpts)).mask(this);
  1932. else EventRuler.off(this);
  1933. } 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))))) {
  1934. e.preventDefault();
  1935. } else {
  1936. switch (e.type) {
  1937. case "input":
  1938. if (skipInputEvent === true) {
  1939. skipInputEvent = false;
  1940. return e.preventDefault();
  1941. }
  1942. break;
  1943. case "keydown":
  1944. //Safari 5.1.x - modal dialog fires keypress twice workaround
  1945. skipKeyPressEvent = false;
  1946. skipInputEvent = false;
  1947. break;
  1948. case "keypress":
  1949. if (skipKeyPressEvent === true) {
  1950. return e.preventDefault();
  1951. }
  1952. skipKeyPressEvent = true;
  1953. break;
  1954. case "click":
  1955. if (iemobile || iphone) {
  1956. var that = this, args = arguments;
  1957. setTimeout(function () {
  1958. eventHandler.apply(that, args);
  1959. }, 0);
  1960. return false;
  1961. }
  1962. break;
  1963. }
  1964. // console.log("executed " + e.type);
  1965. var returnVal = eventHandler.apply(this, arguments);
  1966. if (returnVal === false) {
  1967. e.preventDefault();
  1968. e.stopPropagation();
  1969. }
  1970. return returnVal;
  1971. }
  1972. };
  1973. //keep instance of the event
  1974. input.inputmask.events[eventName] = input.inputmask.events[eventName] || [];
  1975. input.inputmask.events[eventName].push(ev);
  1976. if ($.inArray(eventName, ["submit", "reset"]) !== -1) {
  1977. if (input.form != null) $(input.form).on(eventName, ev);
  1978. } else {
  1979. $(input).on(eventName, ev);
  1980. }
  1981. },
  1982. off: function (input, event) {
  1983. if (input.inputmask && input.inputmask.events) {
  1984. var events;
  1985. if (event) {
  1986. events = [];
  1987. events[event] = input.inputmask.events[event];
  1988. } else {
  1989. events = input.inputmask.events;
  1990. }
  1991. $.each(events, function (eventName, evArr) {
  1992. while (evArr.length > 0) {
  1993. var ev = evArr.pop();
  1994. if ($.inArray(eventName, ["submit", "reset"]) !== -1) {
  1995. if (input.form != null) $(input.form).off(eventName, ev);
  1996. } else {
  1997. $(input).off(eventName, ev);
  1998. }
  1999. }
  2000. delete input.inputmask.events[eventName];
  2001. });
  2002. }
  2003. }
  2004. };
  2005. var EventHandlers = {
  2006. keydownEvent: function (e) {
  2007. function isInputEventSupported(eventName) {
  2008. var el = document.createElement("input"),
  2009. evName = "on" + eventName,
  2010. isSupported = (evName in el);
  2011. if (!isSupported) {
  2012. el.setAttribute(evName, "return;");
  2013. isSupported = typeof el[evName] == "function";
  2014. }
  2015. el = null;
  2016. return isSupported;
  2017. }
  2018. var input = this,
  2019. $input = $(input),
  2020. k = e.keyCode,
  2021. pos = caret(input);
  2022. //backspace, delete, and escape get special treatment
  2023. 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
  2024. e.preventDefault(); //stop default action but allow propagation
  2025. handleRemove(input, k, pos);
  2026. writeBuffer(input, getBuffer(true), getMaskSet().p, e, input.inputmask._valueGet() !== getBuffer().join(""));
  2027. if (input.inputmask._valueGet() === getBufferTemplate().join("")) {
  2028. $input.trigger("cleared");
  2029. } else if (isComplete(getBuffer()) === true) {
  2030. $input.trigger("complete");
  2031. }
  2032. } else if (k === Inputmask.keyCode.END || k === Inputmask.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  2033. e.preventDefault();
  2034. var caretPos = seekNext(getLastValidPosition());
  2035. if (!opts.insertMode && caretPos === getMaskSet().maskLength && !e.shiftKey) caretPos--;
  2036. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos, true);
  2037. } else if ((k === Inputmask.keyCode.HOME && !e.shiftKey) || k === Inputmask.keyCode.PAGE_UP) { //Home or page_up
  2038. e.preventDefault();
  2039. caret(input, 0, e.shiftKey ? pos.begin : 0, true);
  2040. } else if (((opts.undoOnEscape && k === Inputmask.keyCode.ESCAPE) || (k === 90 && e.ctrlKey)) && e.altKey !== true) { //escape && undo && #762
  2041. checkVal(input, true, false, undoValue.split(""));
  2042. $input.trigger("click");
  2043. } else if (k === Inputmask.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
  2044. opts.insertMode = !opts.insertMode;
  2045. caret(input, !opts.insertMode && pos.begin === getMaskSet().maskLength ? pos.begin - 1 : pos.begin);
  2046. } else if (opts.tabThrough === true && k === Inputmask.keyCode.TAB) {
  2047. if (e.shiftKey === true) {
  2048. if (getTest(pos.begin).match.fn === null) {
  2049. pos.begin = seekNext(pos.begin);
  2050. }
  2051. pos.end = seekPrevious(pos.begin, true);
  2052. pos.begin = seekPrevious(pos.end, true);
  2053. } else {
  2054. pos.begin = seekNext(pos.begin, true);
  2055. pos.end = seekNext(pos.begin, true);
  2056. if (pos.end < getMaskSet().maskLength) pos.end--;
  2057. }
  2058. if (pos.begin < getMaskSet().maskLength) {
  2059. e.preventDefault();
  2060. caret(input, pos.begin, pos.end);
  2061. }
  2062. } else if (!e.shiftKey) {
  2063. if (opts.insertMode === false) {
  2064. if (k === Inputmask.keyCode.RIGHT) {
  2065. setTimeout(function () {
  2066. var caretPos = caret(input);
  2067. caret(input, caretPos.begin);
  2068. }, 0);
  2069. } else if (k === Inputmask.keyCode.LEFT) {
  2070. setTimeout(function () {
  2071. var caretPos = caret(input);
  2072. caret(input, isRTL ? caretPos.begin + 1 : caretPos.begin - 1);
  2073. }, 0);
  2074. }
  2075. }
  2076. }
  2077. opts.onKeyDown.call(this, e, getBuffer(), caret(input).begin, opts);
  2078. ignorable = $.inArray(k, opts.ignorables) !== -1;
  2079. },
  2080. keypressEvent: function (e, checkval, writeOut, strict, ndx) {
  2081. var input = this,
  2082. $input = $(input),
  2083. k = e.which || e.charCode || e.keyCode;
  2084. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  2085. if (k === Inputmask.keyCode.ENTER && undoValue !== getBuffer().join("")) {
  2086. undoValue = getBuffer().join("");
  2087. // e.preventDefault();
  2088. setTimeout(function () {
  2089. $input.trigger("change");
  2090. }, 0);
  2091. }
  2092. return true;
  2093. } else {
  2094. if (k) {
  2095. //special treat the decimal separator
  2096. if (k === 46 && e.shiftKey === false && opts.radixPoint !== "") k = opts.radixPoint.charCodeAt(0);
  2097. var pos = checkval ? {
  2098. begin: ndx,
  2099. end: ndx
  2100. } : caret(input),
  2101. forwardPosition, c = String.fromCharCode(k);
  2102. getMaskSet().writeOutBuffer = true;
  2103. var valResult = isValid(pos, c, strict);
  2104. if (valResult !== false) {
  2105. resetMaskSet(true);
  2106. forwardPosition = valResult.caret !== undefined ? valResult.caret : checkval ? valResult.pos + 1 : seekNext(valResult.pos);
  2107. getMaskSet().p = forwardPosition; //needed for checkval
  2108. }
  2109. if (writeOut !== false) {
  2110. var self = this;
  2111. setTimeout(function () {
  2112. opts.onKeyValidation.call(self, k, valResult, opts);
  2113. }, 0);
  2114. if (getMaskSet().writeOutBuffer && valResult !== false) {
  2115. var buffer = getBuffer();
  2116. writeBuffer(input, buffer, (opts.numericInput && valResult.caret === undefined) ? seekPrevious(forwardPosition) : forwardPosition, e, checkval !== true);
  2117. if (checkval !== true) {
  2118. setTimeout(function () { //timeout needed for IE
  2119. if (isComplete(buffer) === true) $input.trigger("complete");
  2120. }, 0);
  2121. }
  2122. }
  2123. }
  2124. e.preventDefault();
  2125. if (checkval) {
  2126. valResult.forwardPosition = forwardPosition;
  2127. return valResult;
  2128. }
  2129. }
  2130. }
  2131. },
  2132. pasteEvent: function (e) {
  2133. var input = this,
  2134. ev = e.originalEvent || e,
  2135. $input = $(input),
  2136. inputValue = input.inputmask._valueGet(true),
  2137. caretPos = caret(input),
  2138. tempValue;
  2139. if (isRTL) {
  2140. tempValue = caretPos.end;
  2141. caretPos.end = caretPos.begin;
  2142. caretPos.begin = tempValue;
  2143. }
  2144. var valueBeforeCaret = inputValue.substr(0, caretPos.begin),
  2145. valueAfterCaret = inputValue.substr(caretPos.end, inputValue.length);
  2146. if (valueBeforeCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(0, caretPos.begin).join("")) valueBeforeCaret = "";
  2147. if (valueAfterCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(caretPos.end).join("")) valueAfterCaret = "";
  2148. if (isRTL) {
  2149. tempValue = valueBeforeCaret;
  2150. valueBeforeCaret = valueAfterCaret;
  2151. valueAfterCaret = tempValue;
  2152. }
  2153. if (window.clipboardData && window.clipboardData.getData) { // IE
  2154. inputValue = valueBeforeCaret + window.clipboardData.getData("Text") + valueAfterCaret;
  2155. } else if (ev.clipboardData && ev.clipboardData.getData) {
  2156. inputValue = valueBeforeCaret + ev.clipboardData.getData("text/plain") + valueAfterCaret;
  2157. } else return true; //allow native paste event as fallback ~ masking will continue by inputfallback
  2158. var pasteValue = inputValue;
  2159. if ($.isFunction(opts.onBeforePaste)) {
  2160. pasteValue = opts.onBeforePaste(inputValue, opts);
  2161. if (pasteValue === false) {
  2162. return e.preventDefault();
  2163. }
  2164. if (!pasteValue) {
  2165. pasteValue = inputValue;
  2166. }
  2167. }
  2168. checkVal(input, false, false, isRTL ? pasteValue.split("").reverse() : pasteValue.toString().split(""));
  2169. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()), e, undoValue !== getBuffer().join(""));
  2170. if (isComplete(getBuffer()) === true) {
  2171. $input.trigger("complete");
  2172. }
  2173. return e.preventDefault();
  2174. },
  2175. inputFallBackEvent: function (e) { //fallback when keypress fails
  2176. var input = this,
  2177. inputValue = input.inputmask._valueGet();
  2178. if (getBuffer().join("") !== inputValue) {
  2179. var caretPos = caret(input);
  2180. inputValue = inputValue.replace(new RegExp("(" + Inputmask.escapeRegex(getBufferTemplate().join("")) + ")*"), "");
  2181. if (iemobile) { //iemobile just set the character at the end althought the caret position is correctly set
  2182. var inputChar = inputValue.replace(getBuffer().join(""), "");
  2183. if (inputChar.length === 1) {
  2184. var keypress = new $.Event("keypress");
  2185. keypress.which = inputChar.charCodeAt(0);
  2186. EventHandlers.keypressEvent.call(input, keypress, true, true, false, getMaskSet().validPositions[caretPos.begin - 1] ? caretPos.begin : caretPos.begin - 1);
  2187. return false;
  2188. }
  2189. }
  2190. if (caretPos.begin > inputValue.length) {
  2191. caret(input, inputValue.length);
  2192. caretPos = caret(input);
  2193. }
  2194. //detect & treat possible backspace before static
  2195. if ((getBuffer().length - inputValue.length) === 1 && inputValue.charAt(caretPos.begin) !== getBuffer()[caretPos.begin] && inputValue.charAt(caretPos.begin + 1) !== getBuffer()[caretPos.begin] && !isMask(caretPos.begin)) {
  2196. e.keyCode = Inputmask.keyCode.BACKSPACE;
  2197. EventHandlers.keydownEvent.call(input, e);
  2198. } else {
  2199. var stickyParts = [], bufferTemplate = getBufferTemplate().join("");
  2200. stickyParts.push(inputValue.substr(0, caretPos.begin));
  2201. stickyParts.push(inputValue.substr(caretPos.begin));
  2202. while (inputValue.match(Inputmask.escapeRegex(bufferTemplate) + "$") === null) {
  2203. bufferTemplate = bufferTemplate.slice(1);
  2204. }
  2205. inputValue = inputValue.replace(bufferTemplate, "");
  2206. if ($.isFunction(opts.onBeforeMask)) inputValue = opts.onBeforeMask(inputValue, opts) || inputValue;
  2207. checkVal(input, true, false, inputValue.split(""), e);
  2208. //correct caret position
  2209. var currentPos = caret(input).begin, currentValue = input.inputmask._valueGet();
  2210. if (currentValue.indexOf(stickyParts[0]) === 0 && currentPos !== stickyParts[0].length) {
  2211. caret(input, stickyParts[0].length);
  2212. if (android) { //caret is set by android after inputevent
  2213. setTimeout(function () {
  2214. caret(input, stickyParts[0].length);
  2215. }, 0);
  2216. }
  2217. } else {
  2218. var pos2 = currentValue.indexOf(stickyParts[1]);
  2219. if (currentPos > pos2) {
  2220. caret(input, pos2);
  2221. if (android) { //caret is set by android after inputevent
  2222. setTimeout(function () {
  2223. caret(input, pos2);
  2224. }, 0);
  2225. }
  2226. }
  2227. }
  2228. if (isComplete(getBuffer()) === true) {
  2229. $(input).trigger("complete");
  2230. }
  2231. }
  2232. e.preventDefault();
  2233. }
  2234. },
  2235. setValueEvent: function (e) {
  2236. this.inputmask.refreshValue = false;
  2237. var input = this,
  2238. value = input.inputmask._valueGet(true);
  2239. if ($.isFunction(opts.onBeforeMask)) value = opts.onBeforeMask(value, opts) || value;
  2240. value = value.split("");
  2241. checkVal(input, true, false, isRTL ? value.reverse() : value);
  2242. undoValue = getBuffer().join("");
  2243. if ((opts.clearMaskOnLostFocus || opts.clearIncomplete) && input.inputmask._valueGet() === getBufferTemplate().join("")) {
  2244. input.inputmask._valueSet("");
  2245. }
  2246. }
  2247. ,
  2248. focusEvent: function (e) {
  2249. var input = this,
  2250. nptValue = input.inputmask._valueGet();
  2251. if (opts.showMaskOnFocus && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue === ""))) {
  2252. if (input.inputmask._valueGet() !== getBuffer().join("")) {
  2253. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
  2254. } else if (mouseEnter === false) { //only executed on focus without mouseenter
  2255. caret(input, seekNext(getLastValidPosition()));
  2256. }
  2257. }
  2258. if (opts.positionCaretOnTab === true && mouseEnter === false) {
  2259. EventHandlers.clickEvent.apply(input, [e, true]);
  2260. }
  2261. undoValue = getBuffer().join("");
  2262. }
  2263. ,
  2264. mouseleaveEvent: function (e) {
  2265. var input = this;
  2266. mouseEnter = false;
  2267. if (opts.clearMaskOnLostFocus && document.activeElement !== input) {
  2268. var buffer = getBuffer().slice(),
  2269. nptValue = input.inputmask._valueGet();
  2270. if (nptValue !== input.getAttribute("placeholder") && nptValue !== "") {
  2271. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  2272. buffer = [];
  2273. } else { //clearout optional tail of the mask
  2274. clearOptionalTail(buffer);
  2275. }
  2276. writeBuffer(input, buffer);
  2277. }
  2278. }
  2279. }
  2280. ,
  2281. clickEvent: function (e, tabbed) {
  2282. function doRadixFocus(clickPos) {
  2283. if (opts.radixPoint !== "") {
  2284. var vps = getMaskSet().validPositions;
  2285. if (vps[clickPos] === undefined || (vps[clickPos].input === getPlaceholder(clickPos))) {
  2286. if (clickPos < seekNext(-1)) return true;
  2287. var radixPos = $.inArray(opts.radixPoint, getBuffer());
  2288. if (radixPos !== -1) {
  2289. for (var vp in vps) {
  2290. if (radixPos < vp && vps[vp].input !== getPlaceholder(vp)) {
  2291. return false;
  2292. }
  2293. }
  2294. return true;
  2295. }
  2296. }
  2297. }
  2298. return false;
  2299. }
  2300. var input = this;
  2301. setTimeout(function () { //needed for Chrome ~ initial selection clears after the clickevent
  2302. if (document.activeElement === input) {
  2303. var selectedCaret = caret(input);
  2304. if (tabbed) {
  2305. if (isRTL)
  2306. selectedCaret.end = selectedCaret.begin;
  2307. else
  2308. selectedCaret.begin = selectedCaret.end;
  2309. }
  2310. if (selectedCaret.begin === selectedCaret.end) {
  2311. switch (opts.positionCaretOnClick) {
  2312. case "none":
  2313. break;
  2314. case "radixFocus":
  2315. if (doRadixFocus(selectedCaret.begin)) {
  2316. var radixPos = getBuffer().join("").indexOf(opts.radixPoint);
  2317. caret(input, opts.numericInput ? seekNext(radixPos) : radixPos);
  2318. break;
  2319. }
  2320. default: //lvp:
  2321. var clickPosition = selectedCaret.begin,
  2322. lvclickPosition = getLastValidPosition(clickPosition, true),
  2323. lastPosition = seekNext(lvclickPosition);
  2324. if (clickPosition < lastPosition) {
  2325. caret(input, !isMask(clickPosition) && !isMask(clickPosition - 1) ? seekNext(clickPosition) : clickPosition);
  2326. } else {
  2327. var placeholder = getPlaceholder(lastPosition);
  2328. if ((placeholder !== "" && getBuffer()[lastPosition] !== placeholder && getTest(lastPosition).match.optionalQuantifier !== true) || (!isMask(lastPosition) && getTest(lastPosition).match.def === placeholder)) {
  2329. lastPosition = seekNext(lastPosition);
  2330. }
  2331. caret(input, lastPosition);
  2332. }
  2333. break;
  2334. }
  2335. }
  2336. }
  2337. }, 0);
  2338. }
  2339. ,
  2340. dblclickEvent: function (e) {
  2341. var input = this;
  2342. setTimeout(function () {
  2343. caret(input, 0, seekNext(getLastValidPosition()));
  2344. }, 0);
  2345. }
  2346. ,
  2347. cutEvent: function (e) {
  2348. var input = this,
  2349. $input = $(input),
  2350. pos = caret(input),
  2351. ev = e.originalEvent || e;
  2352. //correct clipboardData
  2353. var clipboardData = window.clipboardData || ev.clipboardData,
  2354. clipData = isRTL ? getBuffer().slice(pos.end, pos.begin) : getBuffer().slice(pos.begin, pos.end);
  2355. clipboardData.setData("text", isRTL ? clipData.reverse().join("") : clipData.join(""));
  2356. if (document.execCommand) document.execCommand("copy"); // copy selected content to system clipbaord
  2357. handleRemove(input, Inputmask.keyCode.DELETE, pos);
  2358. writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join(""));
  2359. if (input.inputmask._valueGet() === getBufferTemplate().join("")) {
  2360. $input.trigger("cleared");
  2361. }
  2362. }
  2363. ,
  2364. blurEvent: function (e) {
  2365. var $input = $(this),
  2366. input = this;
  2367. if (input.inputmask) {
  2368. var nptValue = input.inputmask._valueGet(),
  2369. buffer = getBuffer().slice();
  2370. if (undoValue !== buffer.join("")) {
  2371. setTimeout(function () { //change event should be triggered after the other buffer manipulations on blur
  2372. $input.trigger("change");
  2373. undoValue = buffer.join("");
  2374. }, 0);
  2375. }
  2376. if (nptValue !== "") {
  2377. if (opts.clearMaskOnLostFocus) {
  2378. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  2379. buffer = [];
  2380. } else { //clearout optional tail of the mask
  2381. clearOptionalTail(buffer);
  2382. }
  2383. }
  2384. if (isComplete(buffer) === false) {
  2385. setTimeout(function () {
  2386. $input.trigger("incomplete");
  2387. }, 0);
  2388. if (opts.clearIncomplete) {
  2389. resetMaskSet();
  2390. if (opts.clearMaskOnLostFocus) {
  2391. buffer = [];
  2392. } else {
  2393. buffer = getBufferTemplate().slice();
  2394. }
  2395. }
  2396. }
  2397. writeBuffer(input, buffer, undefined, e);
  2398. }
  2399. }
  2400. }
  2401. ,
  2402. mouseenterEvent: function (e) {
  2403. var input = this;
  2404. mouseEnter = true;
  2405. if (document.activeElement !== input && opts.showMaskOnHover) {
  2406. if (input.inputmask._valueGet() !== getBuffer().join("")) {
  2407. writeBuffer(input, getBuffer());
  2408. }
  2409. }
  2410. }
  2411. ,
  2412. submitEvent: function (e) { //trigger change on submit if any
  2413. if (undoValue !== getBuffer().join("")) {
  2414. $el.trigger("change");
  2415. }
  2416. if (opts.clearMaskOnLostFocus && getLastValidPosition() === -1 && el.inputmask._valueGet && el.inputmask._valueGet() === getBufferTemplate().join("")) {
  2417. el.inputmask._valueSet(""); //clear masktemplete on submit and still has focus
  2418. }
  2419. if (opts.removeMaskOnSubmit) {
  2420. el.inputmask._valueSet(el.inputmask.unmaskedvalue(), true);
  2421. setTimeout(function () {
  2422. writeBuffer(el, getBuffer());
  2423. }, 0);
  2424. }
  2425. }
  2426. ,
  2427. resetEvent: function (e) {
  2428. el.inputmask.refreshValue = true; //indicate a forced refresh when there is a call to the value before leaving the triggering event fn
  2429. setTimeout(function () {
  2430. $el.trigger("setvalue");
  2431. }, 0);
  2432. }
  2433. };
  2434. function initializeColorMask(input) {
  2435. function findCaretPos(clientx) {
  2436. //calculate text width
  2437. var e = document.createElement('span'), caretPos;
  2438. for (var style in computedStyle) { //clone styles
  2439. if (isNaN(style) && style.indexOf("font") !== -1) {
  2440. e.style[style] = computedStyle[style];
  2441. }
  2442. }
  2443. e.style.textTransform = computedStyle.textTransform;
  2444. e.style.letterSpacing = computedStyle.letterSpacing;
  2445. e.style.position = "absolute";
  2446. e.style.height = "auto";
  2447. e.style.width = "auto";
  2448. e.style.visibility = "hidden";
  2449. e.style.whiteSpace = "nowrap";
  2450. document.body.appendChild(e);
  2451. var inputText = input.inputmask._valueGet(), previousWidth = 0, itl;
  2452. for (caretPos = 0, itl = inputText.length; caretPos <= itl; caretPos++) {
  2453. e.innerHTML += inputText.charAt(caretPos) || "_";
  2454. if (e.offsetWidth >= clientx) {
  2455. var offset1 = (clientx - previousWidth);
  2456. var offset2 = e.offsetWidth - clientx;
  2457. e.innerHTML = inputText.charAt(caretPos);
  2458. offset1 -= (e.offsetWidth / 3);
  2459. caretPos = offset1 < offset2 ? caretPos - 1 : caretPos;
  2460. break;
  2461. }
  2462. previousWidth = e.offsetWidth;
  2463. }
  2464. document.body.removeChild(e);
  2465. return caretPos;
  2466. }
  2467. function position() {
  2468. colorMask.style.position = "absolute";
  2469. colorMask.style.top = offset.top + "px";
  2470. colorMask.style.left = offset.left + "px";
  2471. colorMask.style.width = parseInt(input.offsetWidth) - parseInt(computedStyle.paddingLeft) - parseInt(computedStyle.paddingRight) - parseInt(computedStyle.borderLeftWidth) - parseInt(computedStyle.borderRightWidth) + "px";
  2472. colorMask.style.height = parseInt(input.offsetHeight) - parseInt(computedStyle.paddingTop) - parseInt(computedStyle.paddingBottom) - parseInt(computedStyle.borderTopWidth) - parseInt(computedStyle.borderBottomWidth) + "px";
  2473. colorMask.style.lineHeight = colorMask.style.height;
  2474. colorMask.style.zIndex = isNaN(computedStyle.zIndex) ? -1 : computedStyle.zIndex - 1;
  2475. colorMask.style.webkitAppearance = "textfield";
  2476. colorMask.style.mozAppearance = "textfield";
  2477. colorMask.style.Appearance = "textfield";
  2478. }
  2479. var offset = $(input).position(),
  2480. computedStyle = (input.ownerDocument.defaultView || window).getComputedStyle(input, null),
  2481. parentNode = input.parentNode;
  2482. colorMask = document.createElement("div");
  2483. document.body.appendChild(colorMask); //insert at body to prevent css clash :last-child for example
  2484. for (var style in computedStyle) { //clone styles
  2485. if (isNaN(style) && style !== "cssText" && style.indexOf("webkit") == -1) {
  2486. colorMask.style[style] = computedStyle[style];
  2487. }
  2488. }
  2489. //restyle input
  2490. input.style.backgroundColor = "transparent";
  2491. input.style.color = "transparent";
  2492. input.style.webkitAppearance = "caret";
  2493. input.style.mozAppearance = "caret";
  2494. input.style.Appearance = "caret";
  2495. position();
  2496. //event passthrough
  2497. $(window).on("resize", function (e) {
  2498. offset = $(input).position();
  2499. computedStyle = (input.ownerDocument.defaultView || window).getComputedStyle(input, null);
  2500. position();
  2501. });
  2502. $(input).on("click", function (e) {
  2503. caret(input, findCaretPos(e.clientX));
  2504. return EventHandlers.clickEvent.call(this, [e]);
  2505. });
  2506. $(input).on("keydown", function (e) {
  2507. if (!e.shiftKey && opts.insertMode !== false) {
  2508. setTimeout(function () {
  2509. renderColorMask(input);
  2510. }, 0);
  2511. }
  2512. });
  2513. }
  2514. function renderColorMask(input, buffer, caretPos) {
  2515. function handleStatic() {
  2516. if (!isStatic && (test.fn === null || testPos.input === undefined)) {
  2517. isStatic = true;
  2518. maskTemplate += "<span class='im-static''>"
  2519. } else if (isStatic && (test.fn !== null && testPos.input !== undefined)) {
  2520. isStatic = false;
  2521. maskTemplate += "</span>"
  2522. }
  2523. }
  2524. if (colorMask !== undefined) {
  2525. buffer = buffer || getBuffer();
  2526. if (caretPos === undefined) {
  2527. caretPos = caret(input);
  2528. } else if (caretPos.begin === undefined) {
  2529. caretPos = {begin: caretPos, end: caretPos};
  2530. }
  2531. var maskTemplate = "", isStatic = false;
  2532. if (buffer != "") {
  2533. var ndxIntlzr, pos = 0,
  2534. test, testPos, lvp = getLastValidPosition();
  2535. do {
  2536. if (pos === caretPos.begin && document.activeElement === input) {
  2537. maskTemplate += "<span class='im-caret' style='border-right-width: 1px;border-right-style: solid;'></span>";
  2538. }
  2539. if (getMaskSet().validPositions[pos]) {
  2540. testPos = getMaskSet().validPositions[pos];
  2541. test = testPos.match;
  2542. ndxIntlzr = testPos.locator.slice();
  2543. handleStatic();
  2544. maskTemplate += testPos.input;
  2545. } else {
  2546. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  2547. test = testPos.match;
  2548. ndxIntlzr = testPos.locator.slice();
  2549. if (opts.jitMasking === false || pos < lvp || (typeof opts.jitMasking === "number" && isFinite(opts.jitMasking) && opts.jitMasking > pos)) {
  2550. handleStatic();
  2551. maskTemplate += getPlaceholder(pos, test);
  2552. }
  2553. }
  2554. pos++;
  2555. } while ((maxLength === undefined || pos < maxLength) && (test.fn !== null || test.def !== "") || lvp > pos);
  2556. }
  2557. colorMask.innerHTML = maskTemplate;
  2558. }
  2559. }
  2560. function mask(elem) {
  2561. function isElementTypeSupported(input, opts) {
  2562. function patchValueProperty(npt) {
  2563. var valueGet;
  2564. var valueSet;
  2565. function patchValhook(type) {
  2566. if ($.valHooks && ($.valHooks[type] === undefined || $.valHooks[type].inputmaskpatch !== true)) {
  2567. var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) {
  2568. return elem.value;
  2569. };
  2570. var valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
  2571. elem.value = value;
  2572. return elem;
  2573. };
  2574. $.valHooks[type] = {
  2575. get: function (elem) {
  2576. if (elem.inputmask) {
  2577. if (elem.inputmask.opts.autoUnmask) {
  2578. return elem.inputmask.unmaskedvalue();
  2579. } else {
  2580. var result = valhookGet(elem);
  2581. return getLastValidPosition(undefined, undefined, elem.inputmask.maskset.validPositions) !== -1 || opts.nullable !== true ? result : "";
  2582. }
  2583. } else return valhookGet(elem);
  2584. },
  2585. set: function (elem, value) {
  2586. var $elem = $(elem),
  2587. result;
  2588. result = valhookSet(elem, value);
  2589. if (elem.inputmask) {
  2590. $elem.trigger("setvalue");
  2591. }
  2592. return result;
  2593. },
  2594. inputmaskpatch: true
  2595. };
  2596. }
  2597. }
  2598. function getter() {
  2599. if (this.inputmask) {
  2600. return this.inputmask.opts.autoUnmask ?
  2601. this.inputmask.unmaskedvalue() :
  2602. (getLastValidPosition() !== -1 || opts.nullable !== true ?
  2603. (document.activeElement === this && opts.clearMaskOnLostFocus ?
  2604. (isRTL ? clearOptionalTail(getBuffer().slice()).reverse() : clearOptionalTail(getBuffer().slice())).join("") :
  2605. valueGet.call(this)) :
  2606. "");
  2607. } else return valueGet.call(this);
  2608. }
  2609. function setter(value) {
  2610. valueSet.call(this, value);
  2611. if (this.inputmask) {
  2612. $(this).trigger("setvalue");
  2613. }
  2614. }
  2615. function installNativeValueSetFallback(npt) {
  2616. EventRuler.on(npt, "mouseenter", function (event) {
  2617. var $input = $(this),
  2618. input = this,
  2619. value = input.inputmask._valueGet();
  2620. if (value !== getBuffer().join("") /*&& getLastValidPosition() > 0*/) {
  2621. $input.trigger("setvalue");
  2622. }
  2623. });
  2624. }
  2625. if (!npt.inputmask.__valueGet) {
  2626. if (opts.noValuePatching !== true) {
  2627. if (Object.getOwnPropertyDescriptor) {
  2628. if (typeof Object.getPrototypeOf !== "function") {
  2629. Object.getPrototypeOf = typeof "test".__proto__ === "object" ? function (object) {
  2630. return object.__proto__;
  2631. } : function (object) {
  2632. return object.constructor.prototype;
  2633. };
  2634. }
  2635. var valueProperty = Object.getPrototypeOf ? Object.getOwnPropertyDescriptor(Object.getPrototypeOf(npt), "value") : undefined;
  2636. if (valueProperty && valueProperty.get && valueProperty.set) {
  2637. valueGet = valueProperty.get;
  2638. valueSet = valueProperty.set;
  2639. Object.defineProperty(npt, "value", {
  2640. get: getter,
  2641. set: setter,
  2642. configurable: true
  2643. });
  2644. } else if (npt.tagName !== "INPUT") {
  2645. valueGet = function () {
  2646. return this.textContent;
  2647. };
  2648. valueSet = function (value) {
  2649. this.textContent = value;
  2650. };
  2651. Object.defineProperty(npt, "value", {
  2652. get: getter,
  2653. set: setter,
  2654. configurable: true
  2655. });
  2656. }
  2657. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  2658. valueGet = npt.__lookupGetter__("value");
  2659. valueSet = npt.__lookupSetter__("value");
  2660. npt.__defineGetter__("value", getter);
  2661. npt.__defineSetter__("value", setter);
  2662. }
  2663. npt.inputmask.__valueGet = valueGet; //store native property getter
  2664. npt.inputmask.__valueSet = valueSet; //store native property setter
  2665. }
  2666. npt.inputmask._valueGet = function (overruleRTL) {
  2667. return isRTL && overruleRTL !== true ? valueGet.call(this.el).split("").reverse().join("") : valueGet.call(this.el);
  2668. };
  2669. npt.inputmask._valueSet = function (value, overruleRTL) { //null check is needed for IE8 => otherwise converts to "null"
  2670. valueSet.call(this.el, (value === null || value === undefined) ? "" : ((overruleRTL !== true && isRTL) ? value.split("").reverse().join("") : value));
  2671. };
  2672. if (valueGet === undefined) { //jquery.val fallback
  2673. valueGet = function () {
  2674. return this.value;
  2675. };
  2676. valueSet = function (value) {
  2677. this.value = value;
  2678. };
  2679. patchValhook(npt.type);
  2680. installNativeValueSetFallback(npt);
  2681. }
  2682. }
  2683. }
  2684. var elementType = input.getAttribute("type");
  2685. var isSupported = (input.tagName === "INPUT" && $.inArray(elementType, opts.supportsInputType) !== -1) || input.isContentEditable || input.tagName === "TEXTAREA";
  2686. if (!isSupported) {
  2687. if (input.tagName === "INPUT") {
  2688. var el = document.createElement("input");
  2689. el.setAttribute("type", elementType);
  2690. isSupported = el.type === "text"; //apply mask only if the type is not natively supported
  2691. el = null;
  2692. } else isSupported = "partial";
  2693. }
  2694. if (isSupported !== false) {
  2695. patchValueProperty(input);
  2696. }
  2697. return isSupported;
  2698. }
  2699. //unbind all events - to make sure that no other mask will interfere when re-masking
  2700. EventRuler.off(elem);
  2701. var isSupported = isElementTypeSupported(elem, opts);
  2702. if (isSupported !== false) {
  2703. el = elem;
  2704. $el = $(el);
  2705. if (el.dir === "rtl" || opts.rightAlign) {
  2706. el.style.textAlign = "right";
  2707. }
  2708. if (el.dir === "rtl" || opts.numericInput) {
  2709. el.dir = "ltr";
  2710. el.removeAttribute("dir");
  2711. el.inputmask.isRTL = true;
  2712. isRTL = true;
  2713. }
  2714. if (opts.colorMask === true) {
  2715. initializeColorMask(el);
  2716. }
  2717. if (android) {
  2718. if (el.hasOwnProperty("inputmode")) {
  2719. el.inputmode = opts.inputmode;
  2720. el.setAttribute("inputmode", opts.inputmode);
  2721. }
  2722. if (opts.androidHack === "rtfm") {
  2723. if (opts.colorMask !== true) {
  2724. initializeColorMask(el);
  2725. }
  2726. el.type = "password";
  2727. }
  2728. }
  2729. if (isSupported === true) {
  2730. //bind events
  2731. EventRuler.on(el, "submit", EventHandlers.submitEvent);
  2732. EventRuler.on(el, "reset", EventHandlers.resetEvent);
  2733. EventRuler.on(el, "mouseenter", EventHandlers.mouseenterEvent);
  2734. EventRuler.on(el, "blur", EventHandlers.blurEvent);
  2735. EventRuler.on(el, "focus", EventHandlers.focusEvent);
  2736. EventRuler.on(el, "mouseleave", EventHandlers.mouseleaveEvent);
  2737. if (opts.colorMask !== true)
  2738. EventRuler.on(el, "click", EventHandlers.clickEvent);
  2739. EventRuler.on(el, "dblclick", EventHandlers.dblclickEvent);
  2740. EventRuler.on(el, "paste", EventHandlers.pasteEvent);
  2741. EventRuler.on(el, "dragdrop", EventHandlers.pasteEvent);
  2742. EventRuler.on(el, "drop", EventHandlers.pasteEvent);
  2743. EventRuler.on(el, "cut", EventHandlers.cutEvent);
  2744. EventRuler.on(el, "complete", opts.oncomplete);
  2745. EventRuler.on(el, "incomplete", opts.onincomplete);
  2746. EventRuler.on(el, "cleared", opts.oncleared);
  2747. if (!android && opts.inputEventOnly !== true) {
  2748. EventRuler.on(el, "keydown", EventHandlers.keydownEvent);
  2749. EventRuler.on(el, "keypress", EventHandlers.keypressEvent);
  2750. }
  2751. EventRuler.on(el, "compositionstart", $.noop);
  2752. EventRuler.on(el, "compositionupdate", $.noop);
  2753. EventRuler.on(el, "compositionend", $.noop);
  2754. EventRuler.on(el, "keyup", $.noop);
  2755. EventRuler.on(el, "input", EventHandlers.inputFallBackEvent);
  2756. EventRuler.on(el, "beforeinput", $.noop); //https://github.com/w3c/input-events - to implement
  2757. }
  2758. EventRuler.on(el, "setvalue", EventHandlers.setValueEvent);
  2759. //apply mask
  2760. getBufferTemplate(); //initialize the buffer and getmasklength
  2761. if (el.inputmask._valueGet(true) !== "" || opts.clearMaskOnLostFocus === false || document.activeElement === el) {
  2762. var initialValue = $.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(el.inputmask._valueGet(true), opts) || el.inputmask._valueGet(true)) : el.inputmask._valueGet(true);
  2763. if (initialValue !== "") checkVal(el, true, false, isRTL ? initialValue.split("").reverse() : initialValue.split(""));
  2764. var buffer = getBuffer().slice();
  2765. undoValue = buffer.join("");
  2766. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  2767. if (isComplete(buffer) === false) {
  2768. if (opts.clearIncomplete) {
  2769. resetMaskSet();
  2770. }
  2771. }
  2772. if (opts.clearMaskOnLostFocus && document.activeElement !== el) {
  2773. if (getLastValidPosition() === -1) {
  2774. buffer = [];
  2775. } else {
  2776. clearOptionalTail(buffer);
  2777. }
  2778. }
  2779. writeBuffer(el, buffer);
  2780. if (document.activeElement === el) { //position the caret when in focus
  2781. caret(el, seekNext(getLastValidPosition()));
  2782. }
  2783. }
  2784. }
  2785. }
  2786. //action object
  2787. var valueBuffer;
  2788. if (actionObj !== undefined) {
  2789. switch (actionObj.action) {
  2790. case "isComplete":
  2791. el = actionObj.el;
  2792. return isComplete(getBuffer());
  2793. case "unmaskedvalue":
  2794. if (el === undefined || actionObj.value !== undefined) {
  2795. valueBuffer = actionObj.value;
  2796. valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(valueBuffer, opts) || valueBuffer) : valueBuffer).split("");
  2797. checkVal(undefined, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  2798. if ($.isFunction(opts.onBeforeWrite)) opts.onBeforeWrite(undefined, getBuffer(), 0, opts);
  2799. }
  2800. return unmaskedvalue(el);
  2801. case "mask":
  2802. mask(el);
  2803. break;
  2804. case "format":
  2805. valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(actionObj.value, opts) || actionObj.value) : actionObj.value).split("");
  2806. checkVal(undefined, true, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  2807. if (actionObj.metadata) {
  2808. return {
  2809. value: isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join(""),
  2810. metadata: maskScope.call(this, {
  2811. "action": "getmetadata"
  2812. }, maskset, opts)
  2813. };
  2814. }
  2815. return isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join("");
  2816. case "isValid":
  2817. if (actionObj.value) {
  2818. valueBuffer = actionObj.value.split("");
  2819. checkVal(undefined, true, true, isRTL ? valueBuffer.reverse() : valueBuffer);
  2820. } else {
  2821. actionObj.value = getBuffer().join("");
  2822. }
  2823. var buffer = getBuffer();
  2824. var rl = determineLastRequiredPosition(),
  2825. lmib = buffer.length - 1;
  2826. for (; lmib > rl; lmib--) {
  2827. if (isMask(lmib)) break;
  2828. }
  2829. buffer.splice(rl, lmib + 1 - rl);
  2830. return isComplete(buffer) && actionObj.value === getBuffer().join("");
  2831. case "getemptymask":
  2832. return getBufferTemplate().join("");
  2833. case "remove":
  2834. if (el) {
  2835. $el = $(el);
  2836. //writeout the unmaskedvalue
  2837. el.inputmask._valueSet(unmaskedvalue(el));
  2838. //unbind all events
  2839. EventRuler.off(el);
  2840. //restore the value property
  2841. var valueProperty;
  2842. if (Object.getOwnPropertyDescriptor && Object.getPrototypeOf) {
  2843. valueProperty = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el), "value");
  2844. if (valueProperty) {
  2845. if (el.inputmask.__valueGet) {
  2846. Object.defineProperty(el, "value", {
  2847. get: el.inputmask.__valueGet,
  2848. set: el.inputmask.__valueSet,
  2849. configurable: true
  2850. });
  2851. }
  2852. }
  2853. } else if (document.__lookupGetter__ && el.__lookupGetter__("value")) {
  2854. if (el.inputmask.__valueGet) {
  2855. el.__defineGetter__("value", el.inputmask.__valueGet);
  2856. el.__defineSetter__("value", el.inputmask.__valueSet);
  2857. }
  2858. }
  2859. //clear data
  2860. el.inputmask = undefined;
  2861. }
  2862. return el;
  2863. break;
  2864. case "getmetadata":
  2865. if ($.isArray(maskset.metadata)) {
  2866. var maskTarget = getMaskTemplate(true, 0, false).join("");
  2867. $.each(maskset.metadata, function (ndx, mtdt) {
  2868. if (mtdt.mask === maskTarget) {
  2869. maskTarget = mtdt;
  2870. return false;
  2871. }
  2872. });
  2873. return maskTarget;
  2874. }
  2875. return maskset.metadata;
  2876. }
  2877. }
  2878. }
  2879. //make inputmask available
  2880. return Inputmask;
  2881. }))
  2882. ;