inputmask.js 97 KB

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