inputmask.js 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601
  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. function MaskToken(isGroup, isOptional, isQuantifier, isAlternator) {
  314. this.matches = [];
  315. this.isGroup = isGroup || false;
  316. this.isOptional = isOptional || false;
  317. this.isQuantifier = isQuantifier || false;
  318. this.isAlternator = isAlternator || false;
  319. this.quantifier = {
  320. min: 1,
  321. max: 1
  322. };
  323. }
  324. //test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, casing: null/upper/lower, def: definitionSymbol, placeholder: placeholder, mask: real maskDefinition}
  325. function insertTestDefinition(mtoken, element, position) {
  326. var maskdef = opts.definitions[element],
  327. newBlockMarker = mtoken.matches.length === 0;
  328. position = position !== undefined ? position : mtoken.matches.length;
  329. if (maskdef && !escaped) {
  330. maskdef.placeholder = $.isFunction(maskdef.placeholder) ? maskdef.placeholder.call(this, opts) : maskdef.placeholder;
  331. var prevalidators = maskdef.prevalidator,
  332. prevalidatorsL = prevalidators ? prevalidators.length : 0;
  333. for (var i = 1; i < maskdef.cardinality; i++) {
  334. var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [],
  335. validator = prevalidator.validator,
  336. cardinality = prevalidator.cardinality;
  337. mtoken.matches.splice(position++, 0, {
  338. fn: validator ? typeof validator === "string" ? new RegExp(validator) : new function() {
  339. this.test = validator;
  340. } : new RegExp("."),
  341. cardinality: cardinality ? cardinality : 1,
  342. optionality: mtoken.isOptional,
  343. newBlockMarker: newBlockMarker,
  344. casing: maskdef.casing,
  345. def: maskdef.definitionSymbol || element,
  346. placeholder: maskdef.placeholder,
  347. mask: element
  348. });
  349. }
  350. mtoken.matches.splice(position++, 0, {
  351. fn: maskdef.validator ? typeof maskdef.validator == "string" ? new RegExp(maskdef.validator) : new function() {
  352. this.test = maskdef.validator;
  353. } : new RegExp("."),
  354. cardinality: maskdef.cardinality,
  355. optionality: mtoken.isOptional,
  356. newBlockMarker: newBlockMarker,
  357. casing: maskdef.casing,
  358. def: maskdef.definitionSymbol || element,
  359. placeholder: maskdef.placeholder,
  360. mask: element
  361. });
  362. } else {
  363. mtoken.matches.splice(position++, 0, {
  364. fn: null,
  365. cardinality: 0,
  366. optionality: mtoken.isOptional,
  367. newBlockMarker: newBlockMarker,
  368. casing: null,
  369. def: element,
  370. placeholder: undefined,
  371. mask: element
  372. });
  373. escaped = false;
  374. }
  375. }
  376. function verifyGroupMarker(lastMatch, isOpenGroup) {
  377. if (lastMatch["isGroup"]) { //this is not a group but a normal mask => convert
  378. lastMatch.isGroup = false;
  379. insertTestDefinition(lastMatch, opts.groupmarker.start, 0);
  380. if (isOpenGroup !== true)
  381. insertTestDefinition(lastMatch, opts.groupmarker.end);
  382. }
  383. }
  384. function maskCurrentToken(m, currentToken, lastMatch, extraCondition) {
  385. if (currentToken.matches.length > 0 && (extraCondition == undefined || extraCondition)) {
  386. lastMatch = currentToken.matches[currentToken.matches.length - 1];
  387. verifyGroupMarker(lastMatch);
  388. }
  389. insertTestDefinition(currentToken, m);
  390. }
  391. function defaultCase() {
  392. if (openenings.length > 0) {
  393. currentOpeningToken = openenings[openenings.length - 1];
  394. maskCurrentToken(m, currentOpeningToken, lastMatch, !currentOpeningToken.isAlternator);
  395. if (currentOpeningToken.isAlternator) { //handle alternator a | b case
  396. alternator = openenings.pop();
  397. for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
  398. alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group
  399. }
  400. if (openenings.length > 0) {
  401. currentOpeningToken = openenings[openenings.length - 1];
  402. currentOpeningToken.matches.push(alternator);
  403. } else {
  404. currentToken.matches.push(alternator);
  405. }
  406. }
  407. } else {
  408. maskCurrentToken(m, currentToken, lastMatch);
  409. }
  410. }
  411. function reverseTokens(maskToken) {
  412. function reverseStatic(st) {
  413. if (st == opts.optionalmarker.start)
  414. st = opts.optionalmarker.end;
  415. else if (st == opts.optionalmarker.end)
  416. st = opts.optionalmarker.start;
  417. else if (st == opts.groupmarker.start)
  418. st = opts.groupmarker.end;
  419. else if (st == opts.groupmarker.end)
  420. st = opts.groupmarker.start;
  421. return st;
  422. }
  423. maskToken.matches = maskToken.matches.reverse();
  424. for (var match in maskToken.matches) {
  425. var intMatch = parseInt(match);
  426. if (maskToken.matches[match].isQuantifier && maskToken.matches[intMatch + 1] && maskToken.matches[intMatch + 1].isGroup) { //reposition quantifier
  427. var qt = maskToken.matches[match];
  428. maskToken.matches.splice(match, 1);
  429. maskToken.matches.splice(intMatch + 1, 0, qt);
  430. }
  431. if (maskToken.matches[match].matches != undefined) {
  432. maskToken.matches[match] = reverseTokens(maskToken.matches[match]);
  433. } else {
  434. maskToken.matches[match] = reverseStatic(maskToken.matches[match]);
  435. }
  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. var 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. var 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. lvp = getLastValidPosition();
  1603. if (lrp["def"] == undefined || lrp["def"].newBlockMarker || lrp["def"].optionality || lrp["def"].optionalQuantifier) {
  1604. complete = true;
  1605. for (var i = 0; i <= aml; i++) {
  1606. var test = getTestTemplate(i).match;
  1607. if ((test.fn != null && getMaskSet()["validPositions"][i] == undefined && test.optionality !== true && test.optionalQuantifier !== true) || (test.fn == null && buffer[i] != getPlaceholder(i, test))) {
  1608. complete = false;
  1609. break;
  1610. }
  1611. }
  1612. }
  1613. return complete;
  1614. }
  1615. function isSelection(begin, end) {
  1616. return isRTL ? (begin - end) > 1 || ((begin - end) === 1 && opts.insertMode) :
  1617. (end - begin) > 1 || ((end - begin) === 1 && opts.insertMode);
  1618. }
  1619. function installEventRuler(npt) {
  1620. var events = $._data(npt).events,
  1621. inComposition = false;
  1622. $.each(events, function(eventType, eventHandlers) {
  1623. $.each(eventHandlers, function(ndx, eventHandler) {
  1624. if (eventHandler.namespace === "inputmask") {
  1625. var handler = eventHandler.handler;
  1626. eventHandler.handler = function(e) {
  1627. // console.log("triggered " + e.type);
  1628. if (this.inputmask === undefined) { //happens when cloning an object with jquery.clone
  1629. var imOpts = $(this).data("_inputmask_opts");
  1630. if (imOpts)
  1631. (new Inputmask(imOpts)).mask(this);
  1632. else $(this).unbind(".inputmask");
  1633. } else if (e.type !== "setvalue" && (this.disabled || (this.readOnly && !(e.type === "keydown" && (e.ctrlKey && e.keyCode === 67) || e.keyCode === Inputmask.keyCode.TAB))))
  1634. e.preventDefault();
  1635. else {
  1636. switch (e.type) {
  1637. case "input":
  1638. if (skipInputEvent === true || inComposition === true) {
  1639. skipInputEvent = false;
  1640. return e.preventDefault();
  1641. }
  1642. break;
  1643. case "keydown":
  1644. //Safari 5.1.x - modal dialog fires keypress twice workaround
  1645. skipKeyPressEvent = false;
  1646. inComposition = false;
  1647. break;
  1648. case "keypress":
  1649. if (skipKeyPressEvent === true)
  1650. return e.preventDefault();
  1651. skipKeyPressEvent = true;
  1652. break;
  1653. case "compositionstart":
  1654. inComposition = true;
  1655. break;
  1656. case "compositionupdate":
  1657. skipInputEvent = true;
  1658. break;
  1659. case "compositionend":
  1660. inComposition = false;
  1661. break;
  1662. }
  1663. //console.log("executed " + e.type);
  1664. return handler.apply(this, arguments);
  1665. }
  1666. };
  1667. }
  1668. });
  1669. });
  1670. }
  1671. function patchValueProperty(npt) {
  1672. var valueGet;
  1673. var valueSet;
  1674. function patchValhook(type) {
  1675. if ($.valHooks[type] === undefined || $.valHooks[type].inputmaskpatch !== true) {
  1676. var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function(elem) {
  1677. return elem.value;
  1678. };
  1679. var valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function(elem, value) {
  1680. elem.value = value;
  1681. return elem;
  1682. };
  1683. $.valHooks[type] = {
  1684. get: function(elem) {
  1685. var $elem = $(elem);
  1686. if (elem.inputmask) {
  1687. if (elem.inputmask.opts.autoUnmask)
  1688. return elem.inputmask.unmaskedvalue();
  1689. else {
  1690. var result = valhookGet(elem),
  1691. maskset = elem.inputmask.maskset,
  1692. bufferTemplate = maskset._buffer;
  1693. bufferTemplate = bufferTemplate ? bufferTemplate.join("") : "";
  1694. return result !== bufferTemplate ? result : "";
  1695. }
  1696. } else return valhookGet(elem);
  1697. },
  1698. set: function(elem, value) {
  1699. var $elem = $(elem),
  1700. result;
  1701. result = valhookSet(elem, value);
  1702. if (elem.inputmask)
  1703. $elem.triggerHandler("setvalue.inputmask");
  1704. return result;
  1705. },
  1706. inputmaskpatch: true
  1707. };
  1708. }
  1709. }
  1710. function getter() {
  1711. if (this.inputmask)
  1712. return this.inputmask.opts.autoUnmask ? this.inputmask.unmaskedvalue() : (valueGet.call(this) !== getBufferTemplate().join("") ? valueGet.call(this) : "");
  1713. else return valueGet.call(this);
  1714. }
  1715. function setter(value) {
  1716. valueSet.call(this, value);
  1717. if (this.inputmask)
  1718. $(this).triggerHandler("setvalue.inputmask");
  1719. }
  1720. function installNativeValueSetFallback(npt) {
  1721. $(npt).bind("mouseenter.inputmask", function(event) {
  1722. var $input = $(this),
  1723. input = this,
  1724. value = input.inputmask._valueGet();
  1725. if (value !== "" && value !== getBuffer().join(""))
  1726. $input.triggerHandler("setvalue.inputmask");
  1727. });
  1728. //!! the bound handlers are executed in the order they where bound
  1729. //reorder the events - the mouseenter event is internally mapped to the mouseover event
  1730. var events = $._data(npt).events;
  1731. var handlers = events.mouseover;
  1732. if (handlers) {
  1733. var ourHandler = handlers[handlers.length - 1];
  1734. for (var i = handlers.length - 1; i > 0; i--) {
  1735. handlers[i] = handlers[i - 1];
  1736. }
  1737. handlers[0] = ourHandler;
  1738. }
  1739. }
  1740. if (!npt.inputmask.__valueGet) {
  1741. var valueProperty;
  1742. if (Object.getOwnPropertyDescriptor && npt.value === undefined) { // && npt.isContentEditable) {
  1743. valueGet = function() {
  1744. return this.textContent;
  1745. };
  1746. valueSet = function(value) {
  1747. this.textContent = value;
  1748. };
  1749. Object.defineProperty(npt, "value", {
  1750. get: getter,
  1751. set: setter
  1752. });
  1753. } else if ((valueProperty = (Object.getOwnPropertyDescriptor && Object.getOwnPropertyDescriptor(npt, "value"))) && valueProperty.configurable && false) { //experimental for chrome
  1754. npt._value = valueProperty.value;
  1755. valueGet = function() {
  1756. return this._value || "";
  1757. };
  1758. valueSet = function(value) {
  1759. this._value = value;
  1760. this.select();
  1761. this.setRangeText(value);
  1762. this.selectionStart = this.selectionEnd;
  1763. };
  1764. Object.defineProperty(npt, "value", {
  1765. get: getter,
  1766. set: setter
  1767. });
  1768. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  1769. valueGet = npt.__lookupGetter__("value");
  1770. valueSet = npt.__lookupSetter__("value");
  1771. npt.__defineGetter__("value", getter);
  1772. npt.__defineSetter__("value", setter);
  1773. } else { //jquery.val
  1774. valueGet = function() {
  1775. return npt.value;
  1776. };
  1777. valueSet = function(value) {
  1778. npt.value = value;
  1779. };
  1780. patchValhook(npt.type);
  1781. installNativeValueSetFallback(npt);
  1782. }
  1783. npt.inputmask.__valueGet = valueGet; //store native property getter
  1784. npt.inputmask._valueGet = function(overruleRTL) {
  1785. return isRTL && overruleRTL !== true ? valueGet.call(this.el).split("").reverse().join("") : valueGet.call(this.el);
  1786. };
  1787. npt.inputmask.__valueSet = valueSet; //store native property setter
  1788. npt.inputmask._valueSet = function(value) {
  1789. valueSet.call(this.el, isRTL ? value.split("").reverse().join("") : value);
  1790. };
  1791. }
  1792. }
  1793. function handleRemove(input, k, pos, strict) {
  1794. function generalize() {
  1795. if (opts.keepStatic) {
  1796. resetMaskSet(true);
  1797. var validInputs = [],
  1798. lastAlt, positionsClone = $.extend(true, {}, getMaskSet().validPositions);
  1799. //find last alternation
  1800. for (lastAlt = getLastValidPosition(); lastAlt >= 0; lastAlt--) {
  1801. var validPos = getMaskSet().validPositions[lastAlt];
  1802. if (validPos) {
  1803. if (validPos.match.fn != null)
  1804. validInputs.push(validPos.input);
  1805. delete getMaskSet().validPositions[lastAlt];
  1806. if (validPos.alternation !== undefined && validPos.locator[validPos.alternation] === getTestTemplate(lastAlt).locator[validPos.alternation])
  1807. break;
  1808. }
  1809. }
  1810. if (lastAlt > -1)
  1811. while (validInputs.length > 0) {
  1812. getMaskSet().p = seekNext(getLastValidPosition());
  1813. var keypress = $.Event("keypress");
  1814. keypress.which = validInputs.pop().charCodeAt(0);
  1815. keypressEvent.call(input, keypress, true, false, false, getMaskSet().p);
  1816. } else getMaskSet().validPositions = $.extend(true, {}, positionsClone); //restore original positions
  1817. }
  1818. }
  1819. if (opts.numericInput || isRTL) {
  1820. if (k === Inputmask.keyCode.BACKSPACE)
  1821. k = Inputmask.keyCode.DELETE;
  1822. else if (k === Inputmask.keyCode.DELETE)
  1823. k = Inputmask.keyCode.BACKSPACE;
  1824. if (isRTL) {
  1825. var pend = pos.end;
  1826. pos.end = pos.begin;
  1827. pos.begin = pend;
  1828. }
  1829. }
  1830. if (k === Inputmask.keyCode.BACKSPACE && (pos.end - pos.begin < 1 || opts.insertMode === false)) {
  1831. pos.begin = seekPrevious(pos.begin);
  1832. if (getMaskSet()["validPositions"][pos.begin] !== undefined && (getMaskSet()["validPositions"][pos.begin].input === opts.groupSeparator || getMaskSet()["validPositions"][pos.begin].input === opts.radixPoint)) {
  1833. pos.begin--;
  1834. }
  1835. } else if (k == Inputmask.keyCode.DELETE && pos.begin == pos.end) {
  1836. pos.end = isMask(pos.end) ? pos.end + 1 : seekNext(pos.end) + 1;
  1837. if (getMaskSet()["validPositions"][pos.begin] != undefined && (getMaskSet()["validPositions"][pos.begin].input == opts.groupSeparator || getMaskSet()["validPositions"][pos.begin].input == opts.radixPoint)) {
  1838. pos.end++;
  1839. }
  1840. }
  1841. stripValidPositions(pos.begin, pos.end, false, strict);
  1842. if (strict !== true)
  1843. generalize(); //revert the alternation
  1844. var lvp = getLastValidPosition(pos.begin);
  1845. if (lvp < pos.begin) {
  1846. if (lvp == -1) resetMaskSet();
  1847. getMaskSet()["p"] = seekNext(lvp);
  1848. } else if (strict !== true) {
  1849. getMaskSet()["p"] = pos.begin;
  1850. }
  1851. }
  1852. function keydownEvent(e) {
  1853. var input = this,
  1854. $input = $(input),
  1855. k = e.keyCode,
  1856. pos = caret(input);
  1857. //backspace, delete, and escape get special treatment
  1858. if (k == Inputmask.keyCode.BACKSPACE || k == Inputmask.keyCode.DELETE || (iphone && k == 127) || (e.ctrlKey && k == 88 && !isInputEventSupported("cut"))) { //backspace/delete
  1859. e.preventDefault(); //stop default action but allow propagation
  1860. if (k == 88) undoValue = getBuffer().join('');
  1861. handleRemove(input, k, pos);
  1862. writeBuffer(input, getBuffer(), getMaskSet()["p"], e, undoValue != getBuffer().join(''));
  1863. if (input.inputmask._valueGet() == getBufferTemplate().join(''))
  1864. $input.trigger('cleared');
  1865. else if (isComplete(getBuffer()) === true)
  1866. $input.trigger("complete");
  1867. if (opts.showTooltip) { //update tooltip
  1868. $input.prop("title", getMaskSet()["mask"]);
  1869. }
  1870. } else if (k == Inputmask.keyCode.END || k == Inputmask.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  1871. setTimeout(function() {
  1872. var caretPos = seekNext(getLastValidPosition());
  1873. if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--;
  1874. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
  1875. }, 0);
  1876. } else if ((k == Inputmask.keyCode.HOME && !e.shiftKey) || k == Inputmask.keyCode.PAGE_UP) { //Home or page_up
  1877. caret(input, 0, e.shiftKey ? pos.begin : 0);
  1878. } else if (((opts.undoOnEscape && k == Inputmask.keyCode.ESCAPE) || (k == 90 && e.ctrlKey)) && e.altKey !== true) { //escape && undo && #762
  1879. checkVal(input, true, false, undoValue.split(''));
  1880. $input.click();
  1881. } else if (k == Inputmask.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
  1882. opts.insertMode = !opts.insertMode;
  1883. caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin);
  1884. } else if (opts.insertMode == false && !e.shiftKey) {
  1885. if (k == Inputmask.keyCode.RIGHT) {
  1886. setTimeout(function() {
  1887. var caretPos = caret(input);
  1888. caret(input, caretPos.begin);
  1889. }, 0);
  1890. } else if (k == Inputmask.keyCode.LEFT) {
  1891. setTimeout(function() {
  1892. var caretPos = caret(input);
  1893. caret(input, isRTL ? caretPos.begin + 1 : caretPos.begin - 1);
  1894. }, 0);
  1895. }
  1896. }
  1897. opts.onKeyDown.call(this, e, getBuffer(), caret(input).begin, opts);
  1898. ignorable = $.inArray(k, opts.ignorables) != -1;
  1899. }
  1900. function keypressEvent(e, checkval, writeOut, strict, ndx) {
  1901. var input = this,
  1902. $input = $(input),
  1903. k = e.which || e.charCode || e.keyCode;
  1904. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  1905. return true;
  1906. } else {
  1907. if (k) {
  1908. //special treat the decimal separator
  1909. if (k == 46 && e.shiftKey == false && opts.radixPoint == ",") k = 44;
  1910. var pos = checkval ? {
  1911. begin: ndx,
  1912. end: ndx
  1913. } : caret(input),
  1914. forwardPosition, c = String.fromCharCode(k);
  1915. //should we clear a possible selection??
  1916. var isSlctn = isSelection(pos.begin, pos.end);
  1917. if (isSlctn) {
  1918. getMaskSet()["undoPositions"] = $.extend(true, {}, getMaskSet()["validPositions"]); //init undobuffer for recovery when not valid
  1919. handleRemove(input, Inputmask.keyCode.DELETE, pos, true);
  1920. pos.begin = getMaskSet()["p"];
  1921. if (!opts.insertMode) { //preserve some space
  1922. opts.insertMode = !opts.insertMode;
  1923. setValidPosition(pos.begin, strict);
  1924. opts.insertMode = !opts.insertMode;
  1925. }
  1926. isSlctn = !opts.multi;
  1927. }
  1928. getMaskSet()["writeOutBuffer"] = true;
  1929. var p = isRTL && !isSlctn ? pos.end : pos.begin;
  1930. var valResult = isValid(p, c, strict);
  1931. if (valResult !== false) {
  1932. if (valResult !== true) {
  1933. p = valResult.pos != undefined ? valResult.pos : p; //set new position from isValid
  1934. c = valResult.c != undefined ? valResult.c : c; //set new char from isValid
  1935. }
  1936. resetMaskSet(true);
  1937. if (valResult.caret != undefined)
  1938. forwardPosition = valResult.caret;
  1939. else {
  1940. var vps = getMaskSet()["validPositions"];
  1941. if (!opts.keepStatic && (vps[p + 1] != undefined && getTests(p + 1, vps[p].locator.slice(), p).length > 1 || vps[p].alternation != undefined))
  1942. forwardPosition = p + 1;
  1943. else
  1944. forwardPosition = seekNext(p);
  1945. }
  1946. getMaskSet()["p"] = forwardPosition; //needed for checkval
  1947. }
  1948. if (writeOut !== false) {
  1949. var self = this;
  1950. setTimeout(function() {
  1951. opts.onKeyValidation.call(self, valResult, opts);
  1952. }, 0);
  1953. if (getMaskSet()["writeOutBuffer"] && valResult !== false) {
  1954. var buffer = getBuffer();
  1955. writeBuffer(input, buffer, checkval ? undefined : opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition, e, checkval !== true);
  1956. if (checkval !== true) {
  1957. setTimeout(function() { //timeout needed for IE
  1958. if (isComplete(buffer) === true)
  1959. $input.trigger("complete");
  1960. }, 0);
  1961. }
  1962. } else if (isSlctn) {
  1963. getMaskSet()["buffer"] = undefined;
  1964. getMaskSet()["validPositions"] = getMaskSet()["undoPositions"];
  1965. }
  1966. } else if (isSlctn) {
  1967. getMaskSet()["buffer"] = undefined;
  1968. getMaskSet()["validPositions"] = getMaskSet()["undoPositions"];
  1969. }
  1970. if (opts.showTooltip) { //update tooltip
  1971. $input.prop("title", getMaskSet()["mask"]);
  1972. }
  1973. if (checkval && $.isFunction(opts.onBeforeWrite)) {
  1974. var result = opts.onBeforeWrite.call(this, e, getBuffer(), forwardPosition, opts);
  1975. if (result && result["refreshFromBuffer"]) {
  1976. var refresh = result["refreshFromBuffer"];
  1977. refreshFromBuffer(refresh === true ? refresh : refresh["start"], refresh["end"], result["buffer"]);
  1978. resetMaskSet(true);
  1979. if (result.caret) {
  1980. getMaskSet()["p"] = result.caret;
  1981. }
  1982. }
  1983. }
  1984. e.preventDefault();
  1985. if (checkval) {
  1986. return valResult;
  1987. }
  1988. }
  1989. }
  1990. }
  1991. function pasteEvent(e) {
  1992. var input = this,
  1993. $input = $(input),
  1994. inputValue = input.inputmask._valueGet(true),
  1995. caretPos = caret(input);
  1996. //paste event for IE8 and lower I guess ;-)
  1997. if (e.type == "propertychange" && input.inputmask._valueGet().length <= getMaskLength()) {
  1998. return true;
  1999. } else if (e.type == "paste") {
  2000. var valueBeforeCaret = inputValue.substr(0, caretPos.begin),
  2001. valueAfterCaret = inputValue.substr(caretPos.end, inputValue.length);
  2002. if (valueBeforeCaret == getBufferTemplate().slice(0, caretPos.begin).join('')) valueBeforeCaret = "";
  2003. if (valueAfterCaret == getBufferTemplate().slice(caretPos.end).join('')) valueAfterCaret = "";
  2004. if (window.clipboardData && window.clipboardData.getData) { // IE
  2005. inputValue = valueBeforeCaret + window.clipboardData.getData('Text') + valueAfterCaret;
  2006. } else if (e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData) {
  2007. inputValue = valueBeforeCaret + e.originalEvent.clipboardData.getData('text/plain') + valueAfterCaret;
  2008. }
  2009. }
  2010. var pasteValue = inputValue;
  2011. if ($.isFunction(opts.onBeforePaste)) {
  2012. pasteValue = opts.onBeforePaste.call(input, inputValue, opts);
  2013. if (pasteValue === false) {
  2014. e.preventDefault();
  2015. return false;
  2016. }
  2017. if (!pasteValue)
  2018. pasteValue = inputValue;
  2019. }
  2020. checkVal(input, false, false, isRTL ? pasteValue.split('').reverse() : pasteValue.split(''));
  2021. writeBuffer(input, getBuffer(), undefined, e, true);
  2022. $input.click();
  2023. if (isComplete(getBuffer()) === true)
  2024. $input.trigger("complete");
  2025. return false;
  2026. }
  2027. function inputFallBackEvent(e) { //fallback when keypress & compositionevents fail
  2028. var input = this;
  2029. checkVal(input, true, false);
  2030. if (isComplete(getBuffer()) === true)
  2031. $(input).trigger("complete");
  2032. e.preventDefault();
  2033. }
  2034. function compositionStartEvent(e) {
  2035. var input = this;
  2036. undoValue = getBuffer().join('');
  2037. if (compositionData == "" || e.originalEvent.data.indexOf(compositionData) != 0) {
  2038. compositionCaretPos = caret(input);
  2039. }
  2040. }
  2041. function compositionUpdateEvent(e) {
  2042. var input = this,
  2043. caretPos = caret(input);
  2044. if (e.originalEvent.data.indexOf(compositionData) == 0) {
  2045. resetMaskSet();
  2046. caretPos = compositionCaretPos;
  2047. }
  2048. var newData = e.originalEvent.data;
  2049. caret(input, caretPos.begin, caretPos.end);
  2050. for (var i = 0; i < newData.length; i++) {
  2051. var keypress = $.Event("keypress");
  2052. keypress.which = newData.charCodeAt(i);
  2053. skipKeyPressEvent = false;
  2054. ignorable = false;
  2055. keypressEvent.call(input, keypress); //needs update
  2056. }
  2057. setTimeout(function() {
  2058. var forwardPosition = getMaskSet()["p"];
  2059. writeBuffer(input, getBuffer(), opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition);
  2060. }, 0);
  2061. compositionData = e.originalEvent.data;
  2062. }
  2063. function compositionEndEvent(e) {
  2064. //pickup by inputfallback
  2065. }
  2066. function mask(el) {
  2067. $el = $(el);
  2068. //show tooltip
  2069. if (opts.showTooltip)
  2070. $el.prop("title", getMaskSet().mask);
  2071. if (el.dir === "rtl" || opts.rightAlign)
  2072. $el.css("text-align", "right");
  2073. if (el.dir === "rtl" || opts.numericInput) {
  2074. el.dir = "ltr";
  2075. $el.removeAttr("dir");
  2076. el.inputmask.isRTL = true;
  2077. isRTL = true;
  2078. }
  2079. //unbind all events - to make sure that no other mask will interfere when re-masking
  2080. $el.unbind(".inputmask");
  2081. if (($el.is(":input") && isInputTypeSupported($el.attr("type"))) || el.isContentEditable) {
  2082. //bind events
  2083. $el.closest("form").bind("submit", function() { //trigger change on submit if any
  2084. if (undoValue !== getBuffer().join(""))
  2085. $el.change();
  2086. if (opts.clearMaskOnLostFocus && $el[0].inputmask._valueGet && $el[0].inputmask._valueGet() === getBufferTemplate().join(""))
  2087. $el[0].inputmask._valueSet(""); //clear masktemplete on submit and still has focus
  2088. if (opts.removeMaskOnSubmit)
  2089. $el.inputmask("remove");
  2090. }).bind("reset", function() {
  2091. setTimeout(function() {
  2092. $el.triggerHandler("setvalue.inputmask");
  2093. }, 0);
  2094. });
  2095. $el.bind("mouseenter.inputmask", function() {
  2096. var $input = $(this),
  2097. input = this;
  2098. mouseEnter = true;
  2099. if (!$input.is(":focus") && opts.showMaskOnHover)
  2100. if (input.inputmask._valueGet() !== getBuffer().join(""))
  2101. writeBuffer(input, getBuffer());
  2102. }).bind("blur.inputmask", function(e) {
  2103. var $input = $(this),
  2104. input = this;
  2105. if (input.inputmask) {
  2106. var nptValue = input.inputmask._valueGet(),
  2107. buffer = getBuffer().slice();
  2108. firstClick = true;
  2109. if (undoValue !== buffer.join("")) {
  2110. setTimeout(function() { //change event should be triggered after the other buffer manipulations on blur
  2111. $input.change();
  2112. undoValue = buffer.join("");
  2113. }, 0);
  2114. }
  2115. if (nptValue !== "") {
  2116. if (opts.clearMaskOnLostFocus) {
  2117. if (nptValue == getBufferTemplate().join(""))
  2118. buffer = [];
  2119. else { //clearout optional tail of the mask
  2120. clearOptionalTail(buffer);
  2121. }
  2122. }
  2123. if (isComplete(buffer) === false) {
  2124. setTimeout(function() {
  2125. $input.trigger("incomplete");
  2126. }, 0);
  2127. if (opts.clearIncomplete) {
  2128. resetMaskSet();
  2129. if (opts.clearMaskOnLostFocus)
  2130. buffer = [];
  2131. else {
  2132. buffer = getBufferTemplate().slice();
  2133. }
  2134. }
  2135. }
  2136. writeBuffer(input, buffer, undefined, e);
  2137. }
  2138. }
  2139. }).bind("focus.inputmask", function(e) {
  2140. var $input = $(this),
  2141. input = this,
  2142. nptValue = input.inputmask._valueGet();
  2143. if (opts.showMaskOnFocus && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue == ''))) {
  2144. if (input.inputmask._valueGet() != getBuffer().join('')) {
  2145. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
  2146. }
  2147. } else if (mouseEnter === false) { //only executed on focus without mouseenter
  2148. caret(input, seekNext(getLastValidPosition()));
  2149. }
  2150. if (opts.positionCaretOnTab === true) {
  2151. setTimeout(function() {
  2152. caret(input, seekNext(getLastValidPosition()));
  2153. }, 0);
  2154. }
  2155. undoValue = getBuffer().join('');
  2156. }).bind("mouseleave.inputmask", function() {
  2157. var $input = $(this),
  2158. input = this;
  2159. mouseEnter = false;
  2160. if (opts.clearMaskOnLostFocus) {
  2161. var buffer = getBuffer().slice(),
  2162. nptValue = input.inputmask._valueGet();
  2163. if (!$input.is(":focus") && nptValue != $input.attr("placeholder") && nptValue != '') {
  2164. if (nptValue == getBufferTemplate().join(''))
  2165. buffer = [];
  2166. else { //clearout optional tail of the mask
  2167. clearOptionalTail(buffer);
  2168. }
  2169. writeBuffer(input, buffer);
  2170. }
  2171. }
  2172. }).bind("click.inputmask", function() {
  2173. var $input = $(this),
  2174. input = this;
  2175. if ($input.is(":focus")) {
  2176. var selectedCaret = caret(input);
  2177. if (selectedCaret.begin == selectedCaret.end) {
  2178. if (opts.radixFocus && opts.radixPoint != "" && $.inArray(opts.radixPoint, getBuffer()) != -1 && (firstClick || getBuffer().join('') == getBufferTemplate().join(''))) {
  2179. caret(input, $.inArray(opts.radixPoint, getBuffer()));
  2180. firstClick = false;
  2181. } else {
  2182. var clickPosition = selectedCaret.begin,
  2183. lastPosition = seekNext(getLastValidPosition(clickPosition));
  2184. if (clickPosition < lastPosition) {
  2185. caret(input, isMask(clickPosition) ? clickPosition : seekNext(clickPosition));
  2186. } else {
  2187. caret(input, opts.numericInput ? 0 : lastPosition);
  2188. }
  2189. }
  2190. }
  2191. }
  2192. }).bind('dblclick.inputmask', function() {
  2193. var input = this;
  2194. setTimeout(function() {
  2195. caret(input, 0, seekNext(getLastValidPosition()));
  2196. }, 0);
  2197. }).bind(PasteEventType + ".inputmask dragdrop.inputmask drop.inputmask", pasteEvent).bind('cut.inputmask', function(e) {
  2198. skipInputEvent = true; //stop inputFallback
  2199. var input = this,
  2200. $input = $(input),
  2201. pos = caret(input);
  2202. //correct clipboardData
  2203. if (isRTL) {
  2204. var clipboardData = window.clipboardData || e.originalEvent.clipboardData,
  2205. clipData = clipboardData.getData('text').split('').reverse().join('');
  2206. clipboardData.setData('text', clipData);
  2207. }
  2208. handleRemove(input, Inputmask.keyCode.DELETE, pos);
  2209. writeBuffer(input, getBuffer(), getMaskSet()["p"], e, undoValue != getBuffer().join(''));
  2210. if (input.inputmask._valueGet() == getBufferTemplate().join(''))
  2211. $input.trigger('cleared');
  2212. if (opts.showTooltip) { //update tooltip
  2213. $input.prop("title", getMaskSet()["mask"]);
  2214. }
  2215. }).bind('complete.inputmask', opts.oncomplete).bind('incomplete.inputmask', opts.onincomplete).bind('cleared.inputmask', opts.oncleared);
  2216. $el.bind("keydown.inputmask", keydownEvent).bind("keypress.inputmask", keypressEvent);
  2217. if (!androidfirefox) {
  2218. $el.bind("compositionstart.inputmask", compositionStartEvent).bind("compositionupdate.inputmask", compositionUpdateEvent).bind("compositionend.inputmask", compositionEndEvent);
  2219. }
  2220. if (PasteEventType === "paste") {
  2221. $el.bind("input.inputmask", inputFallBackEvent);
  2222. }
  2223. //if (android || androidfirefox || androidchrome || kindle) {
  2224. // $el.unbind("input.inputmask");
  2225. // $el.bind("input.inputmask", mobileInputEvent);
  2226. //}
  2227. }
  2228. $el.bind('setvalue.inputmask', function() {
  2229. var input = this,
  2230. value = input.inputmask._valueGet();
  2231. input.inputmask._valueSet($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call(input, value, opts) || value) : value);
  2232. checkVal(input, true, false);
  2233. undoValue = getBuffer().join('');
  2234. if ((opts.clearMaskOnLostFocus || opts.clearIncomplete) && input.inputmask._valueGet() == getBufferTemplate().join(''))
  2235. input.inputmask._valueSet('');
  2236. });
  2237. patchValueProperty(el);
  2238. //apply mask
  2239. var initialValue = $.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call(el, el.inputmask._valueGet(), opts) || el.inputmask._valueGet()) : el.inputmask._valueGet();
  2240. checkVal(el, true, false, initialValue.split(''));
  2241. var buffer = getBuffer().slice();
  2242. undoValue = buffer.join('');
  2243. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  2244. var activeElement;
  2245. try {
  2246. activeElement = document.activeElement;
  2247. } catch (e) {}
  2248. if (isComplete(buffer) === false) {
  2249. if (opts.clearIncomplete)
  2250. resetMaskSet();
  2251. }
  2252. if (opts.clearMaskOnLostFocus) {
  2253. if (buffer.join('') == getBufferTemplate().join('')) {
  2254. buffer = [];
  2255. } else {
  2256. clearOptionalTail(buffer);
  2257. }
  2258. }
  2259. writeBuffer(el, buffer);
  2260. if (activeElement === el) { //position the caret when in focus
  2261. caret(el, seekNext(getLastValidPosition()));
  2262. }
  2263. installEventRuler(el);
  2264. }
  2265. //action object
  2266. if (actionObj != undefined) {
  2267. switch (actionObj["action"]) {
  2268. case "isComplete":
  2269. el = actionObj["el"]
  2270. $el = $(el);
  2271. maskset = el.inputmask.maskset;
  2272. opts = el.inputmask.opts;
  2273. return isComplete(actionObj["buffer"]);
  2274. case "unmaskedvalue":
  2275. el = actionObj["el"]
  2276. if (el == undefined) {
  2277. //store inputmask instance on the input with element reference
  2278. $el = $({});
  2279. el = $el[0];
  2280. el.inputmask = new Inputmask();
  2281. el.inputmask.opts = opts;
  2282. el.inputmask.el = el;
  2283. el.inputmask.maskset = maskset;
  2284. el.inputmask.isRTL = opts.numericInput;
  2285. if (opts.numericInput) {
  2286. isRTL = true;
  2287. }
  2288. var valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call($el, actionObj["value"], opts) || actionObj["value"]) : actionObj["value"]).split('');
  2289. checkVal($el, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  2290. $.isFunction(opts.onBeforeWrite) && opts.onBeforeWrite.call(this, undefined, getBuffer(), 0, opts);
  2291. } else $el = $(el);
  2292. maskset = el.inputmask.maskset;
  2293. opts = el.inputmask.opts;
  2294. isRTL = el.inputmask.isRTL;
  2295. return unmaskedvalue($el);
  2296. case "mask":
  2297. undoValue = getBuffer().join('');
  2298. mask(actionObj["el"]);
  2299. break;
  2300. case "format":
  2301. $el = $({});
  2302. //store inputmask instance on the input with element reference
  2303. $el[0].inputmask = new Inputmask();
  2304. $el[0].inputmask.opts = opts;
  2305. $el[0].inputmask.el = $el[0];
  2306. $el[0].inputmask.maskset = maskset;
  2307. $el[0].inputmask.isRTL = opts.numericInput;
  2308. if (opts.numericInput) {
  2309. isRTL = true;
  2310. }
  2311. var valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call($el, actionObj["value"], opts) || actionObj["value"]) : actionObj["value"]).split('');
  2312. checkVal($el, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  2313. $.isFunction(opts.onBeforeWrite) && opts.onBeforeWrite.call(this, undefined, getBuffer(), 0, opts);
  2314. if (actionObj["metadata"]) {
  2315. return {
  2316. value: isRTL ? getBuffer().slice().reverse().join('') : getBuffer().join(''),
  2317. metadata: $el.inputmask("getmetadata")
  2318. }
  2319. }
  2320. return isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join("");
  2321. case "isValid":
  2322. $el = $({});
  2323. //store inputmask instance on the input with element reference
  2324. $el[0].inputmask = new Inputmask();
  2325. $el[0].inputmask.opts = opts;
  2326. $el[0].inputmask.el = $el[0];
  2327. $el[0].inputmask.maskset = maskset;
  2328. $el[0].inputmask.isRTL = opts.numericInput;
  2329. if (opts.numericInput) {
  2330. isRTL = true;
  2331. }
  2332. var valueBuffer = actionObj["value"].split('');
  2333. checkVal($el, false, true, isRTL ? valueBuffer.reverse() : valueBuffer);
  2334. var buffer = getBuffer();
  2335. var rl = determineLastRequiredPosition(),
  2336. lmib = buffer.length - 1;
  2337. for (; lmib > rl; lmib--) {
  2338. if (isMask(lmib)) break;
  2339. }
  2340. buffer.splice(rl, lmib + 1 - rl);
  2341. return isComplete(buffer) && actionObj["value"] == buffer.join('');
  2342. case "getemptymask":
  2343. el = actionObj["el"]
  2344. $el = $(el);
  2345. maskset = el.inputmask.maskset;
  2346. opts = el.inputmask.opts;
  2347. return getBufferTemplate();
  2348. case "remove":
  2349. el = actionObj.el;
  2350. $el = $(el);
  2351. maskset = el.inputmask.maskset;
  2352. opts = el.inputmask.opts;
  2353. //writeout the unmaskedvalue
  2354. el.inputmask._valueSet(unmaskedvalue($el));
  2355. //unbind all events
  2356. $el.unbind(".inputmask");
  2357. //restore the value property
  2358. var valueProperty;
  2359. if (Object.getOwnPropertyDescriptor)
  2360. valueProperty = Object.getOwnPropertyDescriptor(el, "value");
  2361. if (valueProperty && valueProperty.get) {
  2362. if (el.inputmask.__valueGet) {
  2363. Object.defineProperty(el, "value", {
  2364. get: el.inputmask.__valueGet,
  2365. set: el.inputmask.__valueSet
  2366. });
  2367. }
  2368. } else if (document.__lookupGetter__ && el.__lookupGetter__("value")) {
  2369. if (el.inputmask.__valueGet) {
  2370. el.__defineGetter__("value", el.inputmask.__valueGet);
  2371. el.__defineSetter__("value", el.inputmask.__valueSet);
  2372. }
  2373. }
  2374. //clear data
  2375. el.inputmask = undefined;
  2376. break;
  2377. case "getmetadata":
  2378. el = actionObj.el;
  2379. $el = $(el);
  2380. maskset = el.inputmask.maskset;
  2381. opts = el.inputmask.opts;
  2382. if ($.isArray(maskset.metadata)) {
  2383. //find last alternation
  2384. var alternation, lvp = getLastValidPosition();
  2385. for (var firstAlt = lvp; firstAlt >= 0; firstAlt--) {
  2386. if (getMaskSet().validPositions[firstAlt] && getMaskSet().validPositions[firstAlt].alternation !== undefined) {
  2387. alternation = getMaskSet().validPositions[firstAlt].alternation;
  2388. break;
  2389. }
  2390. }
  2391. if (alternation !== undefined)
  2392. return maskset.metadata[getMaskSet().validPositions[lvp].locator[alternation]];
  2393. else return maskset.metadata[0];
  2394. }
  2395. return maskset.metadata;
  2396. }
  2397. }
  2398. }
  2399. //make inputmask available
  2400. window.Inputmask = Inputmask;
  2401. return Inputmask;
  2402. })(jQuery);