jquery.inputmask.js 117 KB

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