inputmask.js 93 KB

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