inputmask.js 101 KB

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