inputmask.js 94 KB

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