inputmask.js 94 KB

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