inputmask.js 94 KB

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