jquery.inputmask.bundle.js 142 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820
  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: 3.0.3
  7. */
  8. (function ($) {
  9. if ($.fn.inputmask === undefined) {
  10. //helper functions
  11. function isInputEventSupported(eventName) {
  12. var el = document.createElement('input'),
  13. eventName = 'on' + eventName,
  14. isSupported = (eventName in el);
  15. if (!isSupported) {
  16. el.setAttribute(eventName, 'return;');
  17. isSupported = typeof el[eventName] == 'function';
  18. }
  19. el = null;
  20. return isSupported;
  21. }
  22. function resolveAlias(aliasStr, options, opts) {
  23. var aliasDefinition = opts.aliases[aliasStr];
  24. if (aliasDefinition) {
  25. if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias, undefined, opts); //alias is another alias
  26. $.extend(true, opts, aliasDefinition); //merge alias definition in the options
  27. $.extend(true, opts, options); //reapply extra given options
  28. return true;
  29. }
  30. return false;
  31. }
  32. function generateMaskSet(opts) {
  33. var ms = [];
  34. function analyseMask(mask) {
  35. var tokenizer = /(?:[?*+]|\{[0-9]+(?:,[0-9\+\*]*)?\})\??|[^.?*+^${[]()|\\]+|./g,
  36. escaped = false;
  37. function maskToken(isGroup, isOptional, isQuantifier, isAlternator) {
  38. this.matches = [];
  39. this.isGroup = isGroup || false;
  40. this.isOptional = isOptional || false;
  41. this.isQuantifier = isQuantifier || false;
  42. this.isAlternator = isAlternator || false;
  43. this.quantifier = { min: 1, max: 1 };
  44. };
  45. //test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, offset: int, casing: null/upper/lower, def: definitionSymbol}
  46. function insertTestDefinition(mtoken, element, position) {
  47. var maskdef = opts.definitions[element];
  48. position = position != undefined ? position : mtoken.matches.length;
  49. if (maskdef && !escaped) {
  50. var prevalidators = maskdef["prevalidator"], prevalidatorsL = prevalidators ? prevalidators.length : 0;
  51. for (var i = 1; i < maskdef.cardinality; i++) {
  52. var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [], validator = prevalidator["validator"], cardinality = prevalidator["cardinality"];
  53. 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, casing: maskdef["casing"], def: maskdef["definitionSymbol"] || element });
  54. }
  55. 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, casing: maskdef["casing"], def: maskdef["definitionSymbol"] || element });
  56. } else {
  57. mtoken.matches.splice(position++, 0, { fn: null, cardinality: 0, optionality: mtoken.isOptional, casing: null, def: element });
  58. escaped = false;
  59. }
  60. }
  61. var currentToken = new maskToken(),
  62. match,
  63. m,
  64. openenings = [],
  65. maskTokens = [];
  66. while (match = tokenizer.exec(mask)) {
  67. m = match[0];
  68. switch (m.charAt(0)) {
  69. case opts.optionalmarker.end:
  70. // optional closing
  71. case opts.groupmarker.end:
  72. // Group closing
  73. var openingToken = openenings.pop();
  74. if (openenings.length > 0) {
  75. openenings[openenings.length - 1]["matches"].push(openingToken);
  76. } else {
  77. currentToken.matches.push(openingToken);
  78. }
  79. break;
  80. case opts.optionalmarker.start:
  81. // optional opening
  82. openenings.push(new maskToken(false, true));
  83. break;
  84. case opts.groupmarker.start:
  85. // Group opening
  86. openenings.push(new maskToken(true));
  87. break;
  88. case opts.quantifiermarker.start:
  89. //Quantifier
  90. var quantifier = new maskToken(false, false, true);
  91. m = m.replace(/[{}]/g, "");
  92. var mq = m.split(","), mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]), mq1 = mq.length == 1 ? mq0 : (isNaN(mq[1]) ? mq[1] : parseInt(mq[1]));
  93. quantifier.quantifier = { min: mq0, max: mq1 };
  94. if (mq1 == "*" || mq1 == "+") opts.greedy = false;
  95. if (openenings.length > 0) {
  96. var matches = openenings[openenings.length - 1]["matches"];
  97. var match = matches.pop();
  98. if (!match["isGroup"]) {
  99. var groupToken = new maskToken(true);
  100. groupToken.matches.push(match);
  101. match = groupToken;
  102. }
  103. matches.push(match);
  104. matches.push(quantifier);
  105. } else {
  106. var match = currentToken.matches.pop();
  107. if (!match["isGroup"]) {
  108. var groupToken = new maskToken(true);
  109. groupToken.matches.push(match);
  110. match = groupToken;
  111. }
  112. currentToken.matches.push(match);
  113. currentToken.matches.push(quantifier);
  114. }
  115. break;
  116. case opts.escapeChar:
  117. escaped = true;
  118. break;
  119. case opts.alternatormarker:
  120. break;
  121. default:
  122. if (openenings.length > 0) {
  123. insertTestDefinition(openenings[openenings.length - 1], m);
  124. } else {
  125. if (currentToken.matches.length > 0) {
  126. var lastMatch = currentToken.matches[currentToken.matches.length - 1];
  127. if (lastMatch["isGroup"]) { //this is not a group but a normal mask => convert
  128. lastMatch.isGroup = false;
  129. insertTestDefinition(lastMatch, opts.groupmarker.start, 0);
  130. insertTestDefinition(lastMatch, opts.groupmarker.end);
  131. }
  132. }
  133. insertTestDefinition(currentToken, m);
  134. }
  135. }
  136. }
  137. if (currentToken.matches.length > 0)
  138. maskTokens.push(currentToken);
  139. //console.log(JSON.stringify(maskTokens));
  140. return maskTokens;
  141. }
  142. function generateMask(mask, metadata) {
  143. if (opts.numericInput) { //TODO FIXME for dynamic masks
  144. mask = mask.split('').reverse().join('');
  145. }
  146. if (mask == undefined || mask == "")
  147. return undefined;
  148. else {
  149. if (opts.repeat > 0 || opts.repeat == "*" || opts.repeat == "+") {
  150. var repeatStart = opts.repeat == "*" ? 0 : (opts.repeat == "+" ? 1 : opts.repeat);
  151. mask = opts.groupmarker.start + mask + opts.groupmarker.end + opts.quantifiermarker.start + repeatStart + "," + opts.repeat + opts.quantifiermarker.end;
  152. }
  153. if ($.inputmask.masksCache[mask] == undefined) {
  154. $.inputmask.masksCache[mask] = {
  155. "mask": mask,
  156. "maskToken": analyseMask(mask),
  157. "validPositions": {},
  158. "_buffer": undefined,
  159. "buffer": undefined,
  160. "tests": {},
  161. "metadata": metadata
  162. };
  163. }
  164. return $.extend(true, {}, $.inputmask.masksCache[mask]);
  165. }
  166. }
  167. if ($.isFunction(opts.mask)) { //allow mask to be a preprocessing fn - should return a valid mask
  168. opts.mask = opts.mask.call(this, opts);
  169. }
  170. if ($.isArray(opts.mask)) {
  171. $.each(opts.mask, function (ndx, msk) {
  172. if (msk["mask"] != undefined) {
  173. ms.push(generateMask(msk["mask"].toString(), msk));
  174. } else {
  175. ms.push(generateMask(msk.toString()));
  176. }
  177. });
  178. } else {
  179. if (opts.mask.length == 1 && opts.greedy == false && opts.repeat != 0) {
  180. opts.placeholder = "";
  181. } //hide placeholder with single non-greedy mask
  182. if (opts.mask["mask"] != undefined) {
  183. ms = generateMask(opts.mask["mask"].toString(), opts.mask);
  184. } else {
  185. ms = generateMask(opts.mask.toString());
  186. }
  187. }
  188. return ms;
  189. }
  190. var msie1x = typeof ScriptEngineMajorVersion === "function"
  191. ? ScriptEngineMajorVersion() //IE11 detection
  192. : new Function("/*@cc_on return @_jscript_version; @*/")() >= 10, //conditional compilation from mickeysoft trick
  193. ua = navigator.userAgent,
  194. iphone = ua.match(new RegExp("iphone", "i")) !== null,
  195. android = ua.match(new RegExp("android.*safari.*", "i")) !== null,
  196. androidchrome = ua.match(new RegExp("android.*chrome.*", "i")) !== null,
  197. androidfirefox = ua.match(new RegExp("android.*firefox.*", "i")) !== null,
  198. 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),
  199. PasteEventType = isInputEventSupported('paste') ? 'paste' : isInputEventSupported('input') ? 'input' : "propertychange";
  200. //if (androidchrome) {
  201. // var browser = navigator.userAgent.match(new RegExp("chrome.*", "i")),
  202. // version = parseInt(new RegExp(/[0-9]+/).exec(browser));
  203. // androidchrome32 = (version == 32);
  204. //}
  205. //masking scope
  206. //actionObj definition see below
  207. function maskScope(maskset, opts, actionObj) {
  208. var isRTL = false,
  209. valueOnFocus = getBuffer().join(''),
  210. $el,
  211. skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
  212. skipInputEvent = false, //skip when triggered from within inputmask
  213. ignorable = false,
  214. maxLength;
  215. //maskset helperfunctions
  216. function getMaskTemplate(baseOnInput, minimalPos, includeInput) {
  217. minimalPos = minimalPos || 0;
  218. var maskTemplate = [], ndxIntlzr, pos = 0, test;
  219. do {
  220. if (baseOnInput === true && getMaskSet()['validPositions'][pos]) {
  221. var validPos = getMaskSet()['validPositions'][pos];
  222. test = validPos["match"];
  223. ndxIntlzr = validPos["locator"].slice();
  224. maskTemplate.push(test["fn"] == null ? test["def"] : (includeInput === true ? validPos["input"] : opts.placeholder.charAt(pos % opts.placeholder.length)));
  225. } else {
  226. var testPos = getTests(pos, true, ndxIntlzr, pos - 1);
  227. testPos = testPos[opts.greedy || minimalPos > pos ? 0 : (testPos.length - 1)];
  228. test = testPos["match"];
  229. ndxIntlzr = testPos["locator"].slice();
  230. maskTemplate.push(test["fn"] == null ? test["def"] : opts.placeholder.charAt(pos % opts.placeholder.length));
  231. }
  232. pos++;
  233. } while ((maxLength == undefined || pos - 1 < maxLength) && test["fn"] != null || (test["fn"] == null && test["def"] != "") || minimalPos >= pos);
  234. maskTemplate.pop(); //drop the last one which is empty
  235. return maskTemplate;
  236. }
  237. function getMaskSet() {
  238. return maskset;
  239. }
  240. function resetMaskSet(soft) {
  241. var maskset = getMaskSet();
  242. maskset["buffer"] = undefined;
  243. maskset["tests"] = {};
  244. if (soft !== true) {
  245. maskset["_buffer"] = undefined;
  246. maskset["validPositions"] = {};
  247. maskset["p"] = -1;
  248. }
  249. }
  250. function getLastValidPosition(closestTo) { //TODO implement closest to
  251. var maskset = getMaskSet();
  252. var lastValidPosition = -1;
  253. for (var posNdx in maskset["validPositions"]) {
  254. var psNdx = parseInt(posNdx);
  255. if (psNdx > lastValidPosition) lastValidPosition = psNdx;
  256. }
  257. return lastValidPosition;
  258. }
  259. function setValidPosition(pos, validTest, strict, fromSetValid) {
  260. if (opts.insertMode && getMaskSet()["validPositions"][pos] != undefined && fromSetValid == undefined) {
  261. //reposition & revalidate others
  262. var positionsClone = $.extend(true, {}, getMaskSet()["validPositions"]);
  263. for (var i = seekPrevious(getMaskLength()) ; i > pos && i >= 0; i--) {
  264. if (isMask(i)) {
  265. var j = seekPrevious(i);
  266. var t = getMaskSet()["validPositions"][j];
  267. if (t != undefined) {
  268. if (getTest(i).def == getTest(j).def && getMaskSet()["validPositions"][i] == undefined && isValid(i, t["input"], strict, true) !== false) {
  269. delete getMaskSet()["validPositions"][j];
  270. }
  271. }
  272. }
  273. }
  274. if (getMaskSet()["validPositions"][pos] == undefined) {
  275. getMaskSet()["validPositions"][pos] = validTest;
  276. } else {
  277. getMaskSet()["validPositions"] = $.extend(true, {}, positionsClone);
  278. return false;
  279. }
  280. } else
  281. getMaskSet()["validPositions"][pos] = validTest;
  282. return true;
  283. }
  284. function stripValidPositions(start, end) {
  285. var i, ml, startPos = seekNext(start - 1);
  286. for (i = start; i < end; i++) { //clear selection
  287. delete getMaskSet()["validPositions"][i];
  288. }
  289. for (i = end, ml = getMaskLength() ; i < ml; i++) { //clear selection
  290. var t = getMaskSet()["validPositions"][i];
  291. var s = getMaskSet()["validPositions"][startPos];
  292. if (t != undefined && s == undefined) {
  293. if (getTest(startPos).def == t.match.def && isValid(startPos, t["input"], true) !== false) {
  294. delete getMaskSet()["validPositions"][i];
  295. }
  296. startPos = seekNext(startPos);
  297. }
  298. }
  299. resetMaskSet(true);
  300. }
  301. function getTest(pos) {
  302. if (getMaskSet()['validPositions'][pos]) {
  303. return getMaskSet()['validPositions'][pos]["match"];
  304. }
  305. return getTests(pos)[0]["match"];
  306. }
  307. function getTests(pos, disableCache, ndxIntlzr, tstPs) {
  308. var maskTokens = getMaskSet()["maskToken"], testPos = ndxIntlzr ? tstPs : 0, ndxInitializer = ndxIntlzr || [0], matches = [], insertStop = false;
  309. function ResolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) { //ndxInitilizer contains a set of indexes to speedup searches in the mtokens
  310. function handleMatch(match, loopNdx, quantifierRecurse) {
  311. var currentPos = testPos;
  312. if (testPos == pos && match.matches == undefined) {
  313. matches.push({ "match": match, "locator": loopNdx.reverse() });
  314. return true;
  315. } else if (match.matches != undefined) {
  316. if (match.isGroup && quantifierRecurse !== true) { //when a group pass along to the quantifier
  317. match = handleMatch(maskToken.matches[tndx + 1], loopNdx);
  318. if (match) return true;
  319. } else if (match.isOptional) {
  320. var optionalToken = match;
  321. match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  322. if (match) {
  323. var latestMatch = matches[matches.length - 1]["match"];
  324. var isFirstMatch = (optionalToken.matches.indexOf(latestMatch) == 0);
  325. if (isFirstMatch) {
  326. insertStop = true; //insert a stop for non greedy
  327. }
  328. //search for next possible match
  329. testPos = currentPos;
  330. }
  331. } else if (match.isAlternator) {
  332. //TODO
  333. } else if (match.isQuantifier && quantifierRecurse !== true) {
  334. var qt = match;
  335. for (var qndx = (ndxInitializer.length > 0 && quantifierRecurse !== true) ? ndxInitializer.shift() : 0; (qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max)) && testPos <= pos; qndx++) {
  336. var tokenGroup = maskToken.matches[maskToken.matches.indexOf(qt) - 1];
  337. match = handleMatch(tokenGroup, [qndx].concat(loopNdx), true);
  338. if (match) {
  339. //get latest match
  340. var latestMatch = matches[matches.length - 1]["match"];
  341. if (qndx > qt.quantifier.min - 1) { //mark optionality
  342. latestMatch.optionalQuantifier = true;
  343. }
  344. var isFirstMatch = (tokenGroup.matches.indexOf(latestMatch) == 0);
  345. if (isFirstMatch) { //search for next possible match
  346. if (qndx > qt.quantifier.min - 1) {
  347. insertStop = true;
  348. testPos = pos; //match the position after the group
  349. break; //stop quantifierloop
  350. } else return true;
  351. } else {
  352. return true;
  353. }
  354. }
  355. }
  356. } else {
  357. match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  358. if (match)
  359. return true;
  360. }
  361. } else testPos++;
  362. }
  363. for (var tndx = (ndxInitializer.length > 0 ? ndxInitializer.shift() : 0) ; tndx < maskToken.matches.length; tndx++) {
  364. if (maskToken.matches[tndx]["isQuantifier"] !== true) {
  365. var match = handleMatch(maskToken.matches[tndx], [tndx].concat(loopNdx), quantifierRecurse);
  366. if (match && testPos == pos) {
  367. return match;
  368. } else if (testPos > pos) {
  369. break;
  370. }
  371. }
  372. }
  373. }
  374. if (disableCache !== true && getMaskSet()['tests'][pos] && !getMaskSet()['validPositions'][pos]) {
  375. return getMaskSet()['tests'][pos];
  376. }
  377. if (ndxIntlzr == undefined) {
  378. var previousPos = pos - 1, test;
  379. while ((test = getMaskSet()['validPositions'][previousPos]) == undefined && previousPos > -1) {
  380. previousPos--;
  381. }
  382. if (test != undefined && previousPos > -1) {
  383. testPos = previousPos;
  384. ndxInitializer = test["locator"].slice();
  385. } else {
  386. previousPos = pos - 1;
  387. while ((test = getMaskSet()['tests'][previousPos]) == undefined && previousPos > -1) {
  388. previousPos--;
  389. }
  390. if (test != undefined && previousPos > -1) {
  391. testPos = previousPos;
  392. ndxInitializer = test[0]["locator"].slice();
  393. }
  394. }
  395. }
  396. for (var mtndx = ndxInitializer.shift() ; mtndx < maskTokens.length; mtndx++) {
  397. var match = ResolveTestFromToken(maskTokens[mtndx], ndxInitializer, [mtndx]);
  398. if ((match && testPos == pos) || testPos > pos) {
  399. break;
  400. }
  401. }
  402. if (matches.length == 0 || (insertStop && matches.length < 2))
  403. matches.push({ "match": { fn: null, cardinality: 0, optionality: true, casing: null, def: "" }, "locator": [] });
  404. getMaskSet()['tests'][pos] = matches;
  405. //console.log(pos + " - " + JSON.stringify(matches));
  406. return matches;
  407. }
  408. function getBufferTemplate() {
  409. if (getMaskSet()['_buffer'] == undefined) {
  410. //generate template
  411. getMaskSet()["_buffer"] = getMaskTemplate(false, 1);
  412. }
  413. return getMaskSet()['_buffer'];
  414. }
  415. function getBuffer() {
  416. if (getMaskSet()['buffer'] == undefined) {
  417. getMaskSet()['buffer'] = getMaskTemplate(true, getLastValidPosition(), true);
  418. }
  419. return getMaskSet()['buffer'];
  420. }
  421. function refreshFromBuffer(start, end) {
  422. var buffer = getBuffer();
  423. for (var i = start; i < end; i++) {
  424. if (buffer[i] != getPlaceholder(i)) {
  425. var ltst = getTests(i, false)[0];
  426. setValidPosition(i, $.extend({}, ltst, { "input": casing(buffer[i], ltst["match"]) }), true);
  427. }
  428. }
  429. }
  430. function casing(elem, test) {
  431. switch (test.casing) {
  432. case "upper":
  433. elem = elem.toUpperCase();
  434. break;
  435. case "lower":
  436. elem = elem.toLowerCase();
  437. break;
  438. }
  439. return elem;
  440. }
  441. function isValid(pos, c, strict, fromSetValid) { //strict true ~ no correction or autofill
  442. strict = strict === true; //always set a value to strict to prevent possible strange behavior in the extensions
  443. function _isValid(position, c, strict, fromSetValid) {
  444. var rslt = false;
  445. $.each(getTests(position, !strict), function (ndx, tst) {
  446. var test = tst["match"];
  447. var loopend = c ? 1 : 0, chrs = '', buffer = getBuffer();
  448. for (var i = test.cardinality; i > loopend; i--) {
  449. chrs += getBufferElement(position - (i - 1));
  450. }
  451. if (c) {
  452. chrs += c;
  453. }
  454. //return is false or a json object => { pos: ??, c: ??} or true
  455. rslt = test.fn != null ?
  456. test.fn.test(chrs, buffer, position, strict, opts)
  457. : (c == test["def"] || c == opts.skipOptionalPartCharacter) && test["def"] != "" ? //non mask
  458. { c: test["def"], pos: position }
  459. : false;
  460. if (rslt !== false) {
  461. var elem = rslt.c != undefined ? rslt.c : c;
  462. elem = elem == opts.skipOptionalPartCharacter ? test["def"] : elem;
  463. var validatedPos = position;
  464. if (rslt["refreshFromBuffer"]) {
  465. var refresh = rslt["refreshFromBuffer"];
  466. strict = true;
  467. validatedPos = rslt.pos != undefined ? rslt.pos : position;
  468. tst = getTests(validatedPos, !strict)[0]; //possible mismatch TODO
  469. if (refresh === true) {
  470. getMaskSet()["validPositions"] = {};
  471. refreshFromBuffer(0, getBuffer().length);
  472. }
  473. else {
  474. refreshFromBuffer(refresh["start"], refresh["end"]);
  475. }
  476. } else if (rslt !== true && rslt["pos"] != position) { //their is a position offset
  477. validatedPos = rslt["pos"];
  478. refreshFromBuffer(position, validatedPos);
  479. tst = getTests(validatedPos, !strict)[0]; //possible mismatch TODO
  480. }
  481. if (ndx > 0) {
  482. resetMaskSet(true);
  483. }
  484. if (!setValidPosition(validatedPos, $.extend({}, tst, { "input": casing(elem, test) }), strict, fromSetValid))
  485. rslt = false;
  486. return false; //break from $.each
  487. }
  488. });
  489. return rslt;
  490. }
  491. var maskPos = pos;
  492. var result = _isValid(maskPos, c, strict, fromSetValid);
  493. if (!strict && (opts.insertMode || getMaskSet()["validPositions"][seekNext(maskPos)] == undefined) && result === false && !isMask(maskPos)) { //does the input match on a further position?
  494. for (var nPos = maskPos + 1, snPos = seekNext(maskPos) ; nPos <= snPos; nPos++) {
  495. result = _isValid(nPos, c, strict, fromSetValid);
  496. if (result !== false) {
  497. maskPos = nPos;
  498. break;
  499. }
  500. }
  501. }
  502. if (result === true) result = { "pos": maskPos };
  503. return result;
  504. }
  505. function isMask(pos) {
  506. var test = getTest(pos);
  507. return test.fn != null ? test.fn : false;
  508. }
  509. function getMaskLength() {
  510. var maskLength;
  511. maxLength = $el.prop('maxLength');
  512. if (maxLength == -1) maxLength = undefined; /* FF sets no defined max length to -1 */
  513. if (opts.greedy == false) { //TODO FIXME OPTIMIZE ME
  514. var lvp = getLastValidPosition() + 1,
  515. test = getTest(lvp);
  516. while (!(test.fn == null && test.def == "")) { //determine last possible position
  517. test = getTest(++lvp);
  518. if (test.optionality !== true) {
  519. var tests = getTests(lvp);
  520. test = tests[tests.length - 1]["match"];
  521. }
  522. }
  523. maskLength = getMaskTemplate(true, lvp).length;
  524. getMaskSet()["tests"] = {}; //cleanup tests
  525. } else
  526. maskLength = getBuffer().length;
  527. return (maxLength == undefined || maskLength < maxLength) ? maskLength : maxLength;
  528. }
  529. function seekNext(pos) {
  530. var maskL = getMaskLength();
  531. if (pos >= maskL) return maskL;
  532. var position = pos;
  533. while (++position < maskL && !isMask(position) && (opts.nojumps !== true || opts.nojumpsThreshold > position)) {
  534. }
  535. return position;
  536. }
  537. function seekPrevious(pos) {
  538. var position = pos;
  539. if (position <= 0) return 0;
  540. while (--position > 0 && !isMask(position)) {
  541. };
  542. return position;
  543. }
  544. function getBufferElement(position) {
  545. return getMaskSet()["validPositions"][position] == undefined ? getPlaceholder(position) : getMaskSet()["validPositions"][position]["input"];
  546. }
  547. function writeBuffer(input, buffer, caretPos) {
  548. input._valueSet(buffer.join(''));
  549. if (caretPos != undefined) {
  550. caret(input, caretPos);
  551. }
  552. }
  553. function getPlaceholder(pos) {
  554. var test = getTest(pos);
  555. return test["fn"] == null ? test["def"] : opts.placeholder.charAt(pos % opts.placeholder.length);
  556. }
  557. function checkVal(input, writeOut, strict, nptvl, intelliCheck) {
  558. var inputValue = nptvl != undefined ? nptvl.slice() : truncateInput(input._valueGet()).split('');
  559. resetMaskSet();
  560. if (writeOut) input._valueSet(""); //initial clear
  561. $.each(inputValue, function (ndx, charCode) {
  562. if (intelliCheck === true) {
  563. var p = getMaskSet()["p"],
  564. lvp = p == -1 ? p : seekPrevious(p),
  565. pos = lvp == -1 ? ndx : seekNext(lvp);
  566. if ($.inArray(charCode, getBufferTemplate().slice(lvp + 1, pos)) == -1) {
  567. keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), writeOut, strict, ndx);
  568. }
  569. } else {
  570. keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), writeOut, strict, ndx);
  571. strict = strict || (ndx > 0 && ndx > getMaskSet()["p"]);
  572. }
  573. });
  574. }
  575. function escapeRegex(str) {
  576. return $.inputmask.escapeRegex.call(this, str);
  577. }
  578. function truncateInput(inputValue) {
  579. return inputValue.replace(new RegExp("(" + escapeRegex(getBufferTemplate().join('')) + ")*$"), "");
  580. }
  581. function clearOptionalTail(input) {
  582. var buffer = getBuffer(), tmpBuffer = buffer.slice(), pos;
  583. for (pos = tmpBuffer.length - 1; pos >= 0; pos--) {
  584. var test = getTest(pos);
  585. if ((test.optionality || test.optionalQuantifier) && tmpBuffer[pos] == getPlaceholder(pos)) {
  586. tmpBuffer.pop();
  587. } else break;
  588. }
  589. writeBuffer(input, tmpBuffer);
  590. }
  591. function unmaskedvalue($input, skipDatepickerCheck) {
  592. if ($input.data('_inputmask') && (skipDatepickerCheck === true || !$input.hasClass('hasDatepicker'))) {
  593. var umValue = $.map(getBuffer(), function (element, index) {
  594. return isMask(index) && isValid(index, element, true) ? element : null;
  595. });
  596. var unmaskedValue = (isRTL ? umValue.reverse() : umValue).join('');
  597. var bufferValue = (isRTL ? getBuffer().reverse() : getBuffer()).join('');
  598. return $.isFunction(opts.onUnMask) ? opts.onUnMask.call($input, bufferValue, unmaskedValue, opts) : unmaskedValue;
  599. } else {
  600. return $input[0]._valueGet();
  601. }
  602. }
  603. function TranslatePosition(pos) {
  604. if (isRTL && typeof pos == 'number' && (!opts.greedy || opts.placeholder != "")) {
  605. var bffrLght = getBuffer().length;
  606. pos = bffrLght - pos;
  607. }
  608. return pos;
  609. }
  610. function caret(input, begin, end) {
  611. var npt = input.jquery && input.length > 0 ? input[0] : input, range;
  612. if (typeof begin == 'number') {
  613. begin = TranslatePosition(begin);
  614. end = TranslatePosition(end);
  615. end = (typeof end == 'number') ? end : begin;
  616. //store caret for multi scope
  617. var data = $(npt).data('_inputmask') || {};
  618. data["caret"] = { "begin": begin, "end": end };
  619. $(npt).data('_inputmask', data);
  620. if (!$(npt).is(':visible')) {
  621. return;
  622. }
  623. npt.scrollLeft = npt.scrollWidth;
  624. if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode
  625. if (npt.setSelectionRange) {
  626. npt.selectionStart = begin;
  627. npt.selectionEnd = end;
  628. } else if (npt.createTextRange) {
  629. range = npt.createTextRange();
  630. range.collapse(true);
  631. range.moveEnd('character', end);
  632. range.moveStart('character', begin);
  633. range.select();
  634. }
  635. } else {
  636. var data = $(npt).data('_inputmask');
  637. if (!$(npt).is(':visible') && data && data["caret"] != undefined) {
  638. begin = data["caret"]["begin"];
  639. end = data["caret"]["end"];
  640. } else if (npt.setSelectionRange) {
  641. begin = npt.selectionStart;
  642. end = npt.selectionEnd;
  643. } else if (document.selection && document.selection.createRange) {
  644. range = document.selection.createRange();
  645. begin = 0 - range.duplicate().moveStart('character', -100000);
  646. end = begin + range.text.length;
  647. }
  648. begin = TranslatePosition(begin);
  649. end = TranslatePosition(end);
  650. return { "begin": begin, "end": end };
  651. }
  652. }
  653. function isComplete(buffer) { //return true / false / undefined (repeat *)
  654. if ($.isFunction(opts.isComplete)) return opts.isComplete.call($el, buffer, opts);
  655. if (opts.repeat == "*") return undefined;
  656. var complete = false,
  657. aml = seekPrevious(getMaskLength());
  658. if (getLastValidPosition() == aml) {
  659. complete = true;
  660. for (var i = 0; i <= aml; i++) {
  661. var mask = isMask(i);
  662. if ((mask && (buffer[i] == undefined || buffer[i] == getPlaceholder(i))) || (!mask && buffer[i] != getPlaceholder(i))) {
  663. complete = false;
  664. break;
  665. }
  666. }
  667. }
  668. return complete;
  669. }
  670. function isSelection(begin, end) {
  671. return isRTL ? (begin - end) > 1 || ((begin - end) == 1 && opts.insertMode) :
  672. (end - begin) > 1 || ((end - begin) == 1 && opts.insertMode);
  673. }
  674. function installEventRuler(npt) {
  675. var events = $._data(npt).events;
  676. $.each(events, function (eventType, eventHandlers) {
  677. $.each(eventHandlers, function (ndx, eventHandler) {
  678. if (eventHandler.namespace == "inputmask") {
  679. if (eventHandler.type != "setvalue") {
  680. var handler = eventHandler.handler;
  681. eventHandler.handler = function (e) {
  682. if (this.readOnly || this.disabled)
  683. e.preventDefault;
  684. else
  685. return handler.apply(this, arguments);
  686. };
  687. }
  688. }
  689. });
  690. });
  691. }
  692. function patchValueProperty(npt) {
  693. function PatchValhook(type) {
  694. if ($.valHooks[type] == undefined || $.valHooks[type].inputmaskpatch != true) {
  695. var valueGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) { return elem.value; };
  696. var valueSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
  697. elem.value = value;
  698. return elem;
  699. };
  700. $.valHooks[type] = {
  701. get: function (elem) {
  702. var $elem = $(elem);
  703. if ($elem.data('_inputmask')) {
  704. if ($elem.data('_inputmask')['opts'].autoUnmask)
  705. return $elem.inputmask('unmaskedvalue');
  706. else {
  707. var result = valueGet(elem),
  708. inputData = $elem.data('_inputmask'),
  709. maskset = inputData['maskset'],
  710. bufferTemplate = maskset['_buffer'];
  711. bufferTemplate = bufferTemplate ? bufferTemplate.join('') : '';
  712. return result != bufferTemplate ? result : '';
  713. }
  714. } else return valueGet(elem);
  715. },
  716. set: function (elem, value) {
  717. var $elem = $(elem);
  718. var result = valueSet(elem, value);
  719. if ($elem.data('_inputmask')) $elem.triggerHandler('setvalue.inputmask');
  720. return result;
  721. },
  722. inputmaskpatch: true
  723. };
  724. }
  725. }
  726. var valueProperty;
  727. if (Object.getOwnPropertyDescriptor)
  728. valueProperty = Object.getOwnPropertyDescriptor(npt, "value");
  729. if (valueProperty && valueProperty.get) {
  730. if (!npt._valueGet) {
  731. var valueGet = valueProperty.get;
  732. var valueSet = valueProperty.set;
  733. npt._valueGet = function () {
  734. return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
  735. };
  736. npt._valueSet = function (value) {
  737. valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
  738. };
  739. Object.defineProperty(npt, "value", {
  740. get: function () {
  741. var $self = $(this), inputData = $(this).data('_inputmask'), maskset = inputData['maskset'];
  742. return inputData && inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : valueGet.call(this) != maskset['_buffer'].join('') ? valueGet.call(this) : '';
  743. },
  744. set: function (value) {
  745. valueSet.call(this, value);
  746. $(this).triggerHandler('setvalue.inputmask');
  747. }
  748. });
  749. }
  750. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  751. if (!npt._valueGet) {
  752. var valueGet = npt.__lookupGetter__("value");
  753. var valueSet = npt.__lookupSetter__("value");
  754. npt._valueGet = function () {
  755. return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
  756. };
  757. npt._valueSet = function (value) {
  758. valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
  759. };
  760. npt.__defineGetter__("value", function () {
  761. var $self = $(this), inputData = $(this).data('_inputmask'), maskset = inputData['maskset'];
  762. return inputData && inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : valueGet.call(this) != maskset['_buffer'].join('') ? valueGet.call(this) : '';
  763. });
  764. npt.__defineSetter__("value", function (value) {
  765. valueSet.call(this, value);
  766. $(this).triggerHandler('setvalue.inputmask');
  767. });
  768. }
  769. } else {
  770. if (!npt._valueGet) {
  771. npt._valueGet = function () { return isRTL ? this.value.split('').reverse().join('') : this.value; };
  772. npt._valueSet = function (value) { this.value = isRTL ? value.split('').reverse().join('') : value; };
  773. }
  774. PatchValhook(npt.type);
  775. }
  776. }
  777. function HandleRemove(input, k, pos) {
  778. if (opts.numericInput || isRTL) {
  779. switch (k) {
  780. case opts.keyCode.BACKSPACE:
  781. k = opts.keyCode.DELETE;
  782. break;
  783. case opts.keyCode.DELETE:
  784. k = opts.keyCode.BACKSPACE;
  785. break;
  786. }
  787. if (isRTL) {
  788. var pend = pos.end;
  789. pos.end = pos.begin;
  790. pos.begin = pend;
  791. }
  792. }
  793. if (pos.begin == pos.end) {
  794. var posBegin = k == opts.keyCode.BACKSPACE ? pos.begin - 1 : pos.begin;
  795. if (opts.isNumeric && opts.radixPoint != "" && getBuffer()[posBegin] == opts.radixPoint) {
  796. pos.begin = (getBuffer().length - 1 == posBegin) /* radixPoint is latest? delete it */ ? pos.begin : k == opts.keyCode.BACKSPACE ? posBegin : seekNext(posBegin);
  797. pos.end = pos.begin;
  798. }
  799. if (k == opts.keyCode.BACKSPACE)
  800. pos.begin = seekPrevious(pos.begin);
  801. else if (k == opts.keyCode.DELETE)
  802. pos.end++;
  803. } else if (pos.end - pos.begin == 1 && !opts.insertMode) {
  804. if (k == opts.keyCode.BACKSPACE)
  805. pos.begin--;
  806. }
  807. stripValidPositions(pos.begin, pos.end);
  808. var firstMaskPos = seekNext(-1);
  809. if (getLastValidPosition() < firstMaskPos) {
  810. getMaskSet()["p"] = firstMaskPos;
  811. } else {
  812. getMaskSet()["p"] = pos.begin;
  813. }
  814. }
  815. function keydownEvent(e) {
  816. //Safari 5.1.x - modal dialog fires keypress twice workaround
  817. skipKeyPressEvent = false;
  818. var input = this, $input = $(input), k = e.keyCode, pos = caret(input);
  819. //backspace, delete, and escape get special treatment
  820. if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iphone && k == 127) || e.ctrlKey && k == 88) { //backspace/delete
  821. e.preventDefault(); //stop default action but allow propagation
  822. if (k == 88) valueOnFocus = getBuffer().join('');
  823. HandleRemove(input, k, pos);
  824. writeBuffer(input, getBuffer(), getMaskSet()["p"]);
  825. if (input._valueGet() == getBufferTemplate().join(''))
  826. $input.trigger('cleared');
  827. if (opts.showTooltip) { //update tooltip
  828. $input.prop("title", getMaskSet()["mask"]);
  829. }
  830. } else if (k == opts.keyCode.END || k == opts.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  831. setTimeout(function () {
  832. var caretPos = seekNext(getLastValidPosition());
  833. if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--;
  834. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
  835. }, 0);
  836. } else if ((k == opts.keyCode.HOME && !e.shiftKey) || k == opts.keyCode.PAGE_UP) { //Home or page_up
  837. caret(input, 0, e.shiftKey ? pos.begin : 0);
  838. } else if (k == opts.keyCode.ESCAPE || (k == 90 && e.ctrlKey)) { //escape && undo
  839. checkVal(input, true, false, valueOnFocus.split(''));
  840. $input.click();
  841. } else if (k == opts.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
  842. opts.insertMode = !opts.insertMode;
  843. caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin);
  844. } else if (opts.insertMode == false && !e.shiftKey) {
  845. if (k == opts.keyCode.RIGHT) {
  846. setTimeout(function () {
  847. var caretPos = caret(input);
  848. caret(input, caretPos.begin);
  849. }, 0);
  850. } else if (k == opts.keyCode.LEFT) {
  851. setTimeout(function () {
  852. var caretPos = caret(input);
  853. caret(input, caretPos.begin - 1);
  854. }, 0);
  855. }
  856. }
  857. var currentCaretPos = caret(input);
  858. var keydownResult = opts.onKeyDown.call(this, e, getBuffer(), opts);
  859. if (keydownResult && keydownResult["refreshFromBuffer"] === true) { //extra stuff to execute on keydown
  860. getMaskSet()["validPositions"] = {};
  861. refreshFromBuffer(0, getBuffer().length);
  862. caret(input, currentCaretPos.begin, currentCaretPos.end);
  863. }
  864. ignorable = $.inArray(k, opts.ignorables) != -1;
  865. }
  866. function keypressEvent(e, checkval, k, writeOut, strict, ndx) {
  867. //Safari 5.1.x - modal dialog fires keypress twice workaround
  868. if (k == undefined && skipKeyPressEvent) return false;
  869. skipKeyPressEvent = true;
  870. var input = this, $input = $(input);
  871. e = e || window.event;
  872. var k = checkval ? k : (e.which || e.charCode || e.keyCode);
  873. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  874. return true;
  875. } else {
  876. if (k) {
  877. //special treat the decimal separator
  878. if (checkval !== true && k == 46 && e.shiftKey == false && opts.radixPoint == ",") k = 44;
  879. var pos, forwardPosition, c = String.fromCharCode(k);
  880. if (checkval) {
  881. var pcaret = strict ? ndx : getLastValidPosition() + 1;
  882. pos = { begin: pcaret, end: pcaret };
  883. } else {
  884. pos = caret(input);
  885. }
  886. //should we clear a possible selection??
  887. var isSlctn = isSelection(pos.begin, pos.end);
  888. if (isSlctn) {
  889. getMaskSet()["undoPositions"] = $.extend(true, {}, getMaskSet()["validPositions"]); //init undobuffer for recovery when not valid
  890. HandleRemove(input, opts.keyCode.DELETE, pos);
  891. if (!opts.insertMode) { //preserve some space
  892. opts.insertMode = !opts.insertMode;
  893. setValidPosition(pos.begin, undefined, strict);
  894. opts.insertMode = !opts.insertMode;
  895. }
  896. isSlctn = !opts.multi;
  897. }
  898. var radixPosition = getBuffer().join('').indexOf(opts.radixPoint);
  899. if (opts.isNumeric && checkval !== true && radixPosition != -1) {
  900. if (opts.greedy && pos.begin <= radixPosition) {
  901. pos.begin = seekPrevious(pos.begin);
  902. pos.end = pos.begin;
  903. } else if (c == opts.radixPoint) {
  904. pos.begin = radixPosition;
  905. pos.end = pos.begin;
  906. }
  907. }
  908. getMaskSet()["writeOutBuffer"] = true;
  909. var p = pos.begin;
  910. var valResult = isValid(p, c, strict);
  911. if (valResult !== false) {
  912. if (valResult !== true) {
  913. p = valResult.pos != undefined ? valResult.pos : p; //set new position from isValid
  914. c = valResult.c != undefined ? valResult.c : c; //set new char from isValid
  915. }
  916. resetMaskSet(true);
  917. forwardPosition = seekNext(p);
  918. getMaskSet()["p"] = forwardPosition; //needed for checkval
  919. }
  920. if (writeOut !== false) {
  921. var self = this;
  922. setTimeout(function () { opts.onKeyValidation.call(self, valResult, opts); }, 0);
  923. if (getMaskSet()["writeOutBuffer"] && valResult !== false) {
  924. var buffer = getBuffer();
  925. var newCaretPosition;
  926. if (checkval) {
  927. newCaretPosition = undefined;
  928. } else if (opts.numericInput) {
  929. if (p > radixPosition) {
  930. newCaretPosition = seekPrevious(forwardPosition);
  931. } else if (c == opts.radixPoint) {
  932. newCaretPosition = forwardPosition - 1;
  933. } else newCaretPosition = seekPrevious(forwardPosition - 1);
  934. } else {
  935. newCaretPosition = forwardPosition;
  936. }
  937. writeBuffer(input, buffer, newCaretPosition);
  938. if (checkval !== true) {
  939. setTimeout(function () { //timeout needed for IE
  940. if (isComplete(buffer) === true)
  941. $input.trigger("complete");
  942. skipInputEvent = true;
  943. $input.trigger("input");
  944. }, 0);
  945. }
  946. } else if (isSlctn) {
  947. getMaskSet()["buffer"] = undefined;
  948. getMaskSet()["validPositions"] = getMaskSet()["undoPositions"];
  949. }
  950. } else if (isSlctn) {
  951. getMaskSet()["buffer"] = undefined;
  952. getMaskSet()["validPositions"] = getMaskSet()["undoPositions"];
  953. }
  954. if (opts.showTooltip) { //update tooltip
  955. $input.prop("title", getMaskSet()["mask"]);
  956. }
  957. //needed for IE8 and below
  958. if (e) e.preventDefault ? e.preventDefault() : e.returnValue = false;
  959. }
  960. }
  961. }
  962. function keyupEvent(e) {
  963. var $input = $(this), input = this, k = e.keyCode, buffer = getBuffer();
  964. var keyupResult = opts.onKeyUp.call(this, e, buffer, opts);
  965. if (keyupResult && keyupResult["refreshFromBuffer"] === true) {
  966. getMaskSet()["validPositions"] = {};
  967. refreshFromBuffer(0, getBuffer().length);
  968. }
  969. if (k == opts.keyCode.TAB && opts.showMaskOnFocus) {
  970. if ($input.hasClass('focus.inputmask') && input._valueGet().length == 0) {
  971. resetMaskSet();
  972. buffer = getBuffer();
  973. writeBuffer(input, buffer);
  974. caret(input, 0);
  975. valueOnFocus = getBuffer().join('');
  976. } else {
  977. writeBuffer(input, buffer);
  978. if (buffer.join('') == getBufferTemplate().join('') && $.inArray(opts.radixPoint, buffer) != -1) {
  979. caret(input, TranslatePosition(0));
  980. $input.click();
  981. } else
  982. caret(input, TranslatePosition(0), TranslatePosition(getMaskLength()));
  983. }
  984. }
  985. }
  986. function pasteEvent(e) {
  987. if (skipInputEvent === true && e.type == "input") {
  988. skipInputEvent = false;
  989. return true;
  990. }
  991. var input = this, $input = $(input);
  992. //paste event for IE8 and lower I guess ;-)
  993. if (e.type == "propertychange" && input._valueGet().length <= getMaskLength()) {
  994. return true;
  995. }
  996. setTimeout(function () {
  997. var pasteValue = $.isFunction(opts.onBeforePaste) ? opts.onBeforePaste.call(input, input._valueGet(), opts) : input._valueGet();
  998. checkVal(input, false, false, pasteValue.split(''), true);
  999. writeBuffer(input, getBuffer());
  1000. if (isComplete(getBuffer()) === true)
  1001. $input.trigger("complete");
  1002. $input.click();
  1003. }, 0);
  1004. }
  1005. function mobileInputEvent(e) {
  1006. var input = this, $input = $(input);
  1007. //backspace in chrome32 only fires input event - detect & treat
  1008. var caretPos = caret(input),
  1009. currentValue = input._valueGet();
  1010. currentValue = currentValue.replace(new RegExp("(" + escapeRegex(getBufferTemplate().join('')) + ")*"), "");
  1011. //correct caretposition for chrome
  1012. if (caretPos.begin > currentValue.length) {
  1013. caret(input, currentValue.length);
  1014. caretPos = caret(input);
  1015. }
  1016. if ((getBuffer().length - currentValue.length) == 1 && currentValue.charAt(caretPos.begin) != getBuffer()[caretPos.begin]
  1017. && currentValue.charAt(caretPos.begin + 1) != getBuffer()[caretPos.begin]
  1018. && !isMask(caretPos.begin)) {
  1019. e.keyCode = opts.keyCode.BACKSPACE;
  1020. keydownEvent.call(input, e);
  1021. } else { //nonnumerics don't fire keypress
  1022. checkVal(input, false, false, currentValue.split(''));
  1023. writeBuffer(input, getBuffer());
  1024. if (isComplete(getBuffer()) === true)
  1025. $input.trigger("complete");
  1026. $input.click();
  1027. }
  1028. e.preventDefault();
  1029. }
  1030. function mask(el) {
  1031. $el = $(el);
  1032. if ($el.is(":input")) {
  1033. //store tests & original buffer in the input element - used to get the unmasked value
  1034. $el.data('_inputmask', {
  1035. 'maskset': maskset,
  1036. 'opts': opts,
  1037. 'isRTL': false
  1038. });
  1039. //show tooltip
  1040. if (opts.showTooltip) {
  1041. $el.prop("title", getMaskSet()["mask"]);
  1042. }
  1043. patchValueProperty(el);
  1044. if (opts.numericInput) opts.isNumeric = opts.numericInput;
  1045. if (el.dir == "rtl" || (opts.numericInput && opts.rightAlignNumerics) || (opts.isNumeric && opts.rightAlignNumerics))
  1046. $el.css("text-align", "right");
  1047. if (el.dir == "rtl" || opts.numericInput) {
  1048. el.dir = "ltr";
  1049. $el.removeAttr("dir");
  1050. var inputData = $el.data('_inputmask');
  1051. inputData['isRTL'] = true;
  1052. $el.data('_inputmask', inputData);
  1053. isRTL = true;
  1054. }
  1055. //unbind all events - to make sure that no other mask will interfere when re-masking
  1056. $el.unbind(".inputmask");
  1057. $el.removeClass('focus.inputmask');
  1058. //bind events
  1059. $el.closest('form').bind("submit", function () { //trigger change on submit if any
  1060. if (valueOnFocus != getBuffer().join('')) {
  1061. $el.change();
  1062. }
  1063. }).bind('reset', function () {
  1064. setTimeout(function () {
  1065. $el.trigger("setvalue");
  1066. }, 0);
  1067. });
  1068. $el.bind("mouseenter.inputmask", function () {
  1069. var $input = $(this), input = this;
  1070. if (!$input.hasClass('focus.inputmask') && opts.showMaskOnHover) {
  1071. if (input._valueGet() != getBuffer().join('')) {
  1072. writeBuffer(input, getBuffer());
  1073. }
  1074. }
  1075. }).bind("blur.inputmask", function () {
  1076. var $input = $(this), input = this, nptValue = input._valueGet(), buffer = getBuffer();
  1077. $input.removeClass('focus.inputmask');
  1078. if (valueOnFocus != getBuffer().join('')) {
  1079. $input.change();
  1080. }
  1081. if (opts.clearMaskOnLostFocus && nptValue != '') {
  1082. if (nptValue == getBufferTemplate().join(''))
  1083. input._valueSet('');
  1084. else { //clearout optional tail of the mask
  1085. clearOptionalTail(input);
  1086. }
  1087. }
  1088. if (isComplete(buffer) === false) {
  1089. $input.trigger("incomplete");
  1090. if (opts.clearIncomplete) {
  1091. resetMaskSet();
  1092. if (opts.clearMaskOnLostFocus)
  1093. input._valueSet('');
  1094. else {
  1095. buffer = getBufferTemplate().slice();
  1096. writeBuffer(input, buffer);
  1097. }
  1098. }
  1099. }
  1100. }).bind("focus.inputmask", function () {
  1101. var $input = $(this), input = this, nptValue = input._valueGet();
  1102. if (opts.showMaskOnFocus && !$input.hasClass('focus.inputmask') && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue == ''))) {
  1103. if (input._valueGet() != getBuffer().join('')) {
  1104. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
  1105. }
  1106. }
  1107. $input.addClass('focus.inputmask');
  1108. valueOnFocus = getBuffer().join('');
  1109. }).bind("mouseleave.inputmask", function () {
  1110. var $input = $(this), input = this;
  1111. if (opts.clearMaskOnLostFocus) {
  1112. if (!$input.hasClass('focus.inputmask') && input._valueGet() != $input.attr("placeholder")) {
  1113. if (input._valueGet() == getBufferTemplate().join('') || input._valueGet() == '')
  1114. input._valueSet('');
  1115. else { //clearout optional tail of the mask
  1116. clearOptionalTail(input);
  1117. }
  1118. }
  1119. }
  1120. }).bind("click.inputmask", function () {
  1121. var input = this;
  1122. setTimeout(function () {
  1123. var selectedCaret = caret(input), buffer = getBuffer();
  1124. if (selectedCaret.begin == selectedCaret.end) {
  1125. var clickPosition = isRTL ? TranslatePosition(selectedCaret.begin) : selectedCaret.begin,
  1126. lvp = getLastValidPosition(clickPosition),
  1127. lastPosition;
  1128. if (opts.isNumeric) {
  1129. lastPosition = opts.skipRadixDance === false && opts.radixPoint != "" && $.inArray(opts.radixPoint, buffer) != -1 ?
  1130. (opts.numericInput ? seekNext($.inArray(opts.radixPoint, buffer)) : $.inArray(opts.radixPoint, buffer)) :
  1131. seekNext(lvp);
  1132. } else {
  1133. lastPosition = seekNext(lvp);
  1134. }
  1135. if (clickPosition < lastPosition) {
  1136. if (isMask(clickPosition))
  1137. caret(input, clickPosition);
  1138. else caret(input, seekNext(clickPosition));
  1139. } else
  1140. caret(input, lastPosition);
  1141. }
  1142. }, 0);
  1143. }).bind('dblclick.inputmask', function () {
  1144. var input = this;
  1145. setTimeout(function () {
  1146. caret(input, 0, seekNext(getLastValidPosition()));
  1147. }, 0);
  1148. }).bind(PasteEventType + ".inputmask dragdrop.inputmask drop.inputmask", pasteEvent
  1149. ).bind('setvalue.inputmask', function () {
  1150. var input = this;
  1151. checkVal(input, true);
  1152. valueOnFocus = getBuffer().join('');
  1153. if (input._valueGet() == getBufferTemplate().join(''))
  1154. input._valueSet('');
  1155. }).bind('complete.inputmask', opts.oncomplete
  1156. ).bind('incomplete.inputmask', opts.onincomplete
  1157. ).bind('cleared.inputmask', opts.oncleared);
  1158. $el.bind("keydown.inputmask", keydownEvent
  1159. ).bind("keypress.inputmask", keypressEvent
  1160. ).bind("keyup.inputmask", keyupEvent);
  1161. // as the other inputevents aren't reliable for the moment we only base on the input event
  1162. // needs follow-up
  1163. if (android || androidfirefox || androidchrome || kindle) {
  1164. $el.attr("autocomplete", "off")
  1165. .attr("autocorrect", "off")
  1166. .attr("autocapitalize", "off")
  1167. .attr("spellcheck", false);
  1168. if (androidfirefox || kindle) {
  1169. $el.unbind("keydown.inputmask", keydownEvent
  1170. ).unbind("keypress.inputmask", keypressEvent
  1171. ).unbind("keyup.inputmask", keyupEvent);
  1172. if (PasteEventType == "input") {
  1173. $el.unbind(PasteEventType + ".inputmask");
  1174. }
  1175. $el.bind("input.inputmask", mobileInputEvent);
  1176. }
  1177. }
  1178. if (msie1x)
  1179. $el.bind("input.inputmask", pasteEvent);
  1180. //apply mask
  1181. var initialValue = $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call(el, el._valueGet(), opts) : el._valueGet();
  1182. checkVal(el, true, false, initialValue.split(''), true);
  1183. valueOnFocus = getBuffer().join('');
  1184. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  1185. var activeElement;
  1186. try {
  1187. activeElement = document.activeElement;
  1188. } catch (e) {
  1189. }
  1190. if (activeElement === el) { //position the caret when in focus
  1191. $el.addClass('focus.inputmask');
  1192. caret(el, seekNext(getLastValidPosition()));
  1193. } else if (opts.clearMaskOnLostFocus) {
  1194. if (getBuffer().join('') == getBufferTemplate().join('')) {
  1195. el._valueSet('');
  1196. } else {
  1197. clearOptionalTail(el);
  1198. }
  1199. } else {
  1200. writeBuffer(el, getBuffer());
  1201. }
  1202. installEventRuler(el);
  1203. }
  1204. }
  1205. //action object
  1206. if (actionObj != undefined) {
  1207. switch (actionObj["action"]) {
  1208. case "isComplete":
  1209. $el = $(actionObj["el"]);
  1210. return isComplete(actionObj["buffer"]);
  1211. case "unmaskedvalue":
  1212. $el = actionObj["$input"];
  1213. isRTL = actionObj["$input"].data('_inputmask')['isRTL'];
  1214. return unmaskedvalue(actionObj["$input"], actionObj["skipDatepickerCheck"]);
  1215. case "mask":
  1216. mask(actionObj["el"]);
  1217. break;
  1218. case "format":
  1219. $el = $({});
  1220. $el.data('_inputmask', {
  1221. 'maskset': maskset,
  1222. 'opts': opts,
  1223. 'isRTL': opts.numericInput
  1224. });
  1225. if (opts.numericInput) {
  1226. opts.isNumeric = opts.numericInput;
  1227. isRTL = true;
  1228. }
  1229. var valueBuffer = actionObj["value"].split('');
  1230. checkVal($el, false, false, isRTL ? valueBuffer.reverse() : valueBuffer, true);
  1231. return isRTL ? getBuffer().reverse().join('') : getBuffer().join('');
  1232. case "isValid":
  1233. $el = $({});
  1234. $el.data('_inputmask', {
  1235. 'maskset': maskset,
  1236. 'opts': opts,
  1237. 'isRTL': opts.numericInput
  1238. });
  1239. if (opts.numericInput) {
  1240. opts.isNumeric = opts.numericInput;
  1241. isRTL = true;
  1242. }
  1243. var valueBuffer = actionObj["value"].split('');
  1244. checkVal($el, false, true, isRTL ? valueBuffer.reverse() : valueBuffer);
  1245. return isComplete(getBuffer());
  1246. }
  1247. }
  1248. };
  1249. function multiMaskScope(el, masksets, opts) {
  1250. function PatchValhookMulti(type) {
  1251. if ($.valHooks[type] == undefined || $.valHooks[type].inputmaskmultipatch != true) {
  1252. var valueGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) { return elem.value; };
  1253. var valueSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
  1254. elem.value = value;
  1255. return elem;
  1256. };
  1257. $.valHooks[type] = {
  1258. get: function (elem) {
  1259. var $elem = $(elem);
  1260. if ($elem.data('_inputmask-multi')) {
  1261. var data = $elem.data('_inputmask-multi');
  1262. return valueGet(data["elmasks"][data["activeMasksetIndex"]]);
  1263. } else return valueGet(elem);
  1264. },
  1265. set: function (elem, value) {
  1266. var $elem = $(elem);
  1267. var result = valueSet(elem, value);
  1268. if ($elem.data('_inputmask-multi')) $elem.triggerHandler('setvalue');
  1269. return result;
  1270. },
  1271. inputmaskmultipatch: true
  1272. };
  1273. }
  1274. }
  1275. function mcaret(input, begin, end) {
  1276. var npt = input.jquery && input.length > 0 ? input[0] : input, range;
  1277. if (typeof begin == 'number') {
  1278. begin = TranslatePosition(begin);
  1279. end = TranslatePosition(end);
  1280. end = (typeof end == 'number') ? end : begin;
  1281. //store caret for multi scope
  1282. if (npt != el) {
  1283. var data = $(npt).data('_inputmask') || {};
  1284. data["caret"] = { "begin": begin, "end": end };
  1285. $(npt).data('_inputmask', data);
  1286. }
  1287. if (!$(npt).is(':visible')) {
  1288. return;
  1289. }
  1290. npt.scrollLeft = npt.scrollWidth;
  1291. if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode
  1292. if (npt.setSelectionRange) {
  1293. npt.selectionStart = begin;
  1294. npt.selectionEnd = end;
  1295. } else if (npt.createTextRange) {
  1296. range = npt.createTextRange();
  1297. range.collapse(true);
  1298. range.moveEnd('character', end);
  1299. range.moveStart('character', begin);
  1300. range.select();
  1301. }
  1302. } else {
  1303. if (!$(npt).is(':visible') && $(npt).data('_inputmask')["caret"] != undefined) {
  1304. var data = $(npt).data('_inputmask');
  1305. begin = data["caret"]["begin"];
  1306. end = data["caret"]["end"];
  1307. } else if (npt.setSelectionRange) {
  1308. begin = npt.selectionStart;
  1309. end = npt.selectionEnd;
  1310. } else if (document.selection && document.selection.createRange) {
  1311. range = document.selection.createRange();
  1312. begin = 0 - range.duplicate().moveStart('character', -100000);
  1313. end = begin + range.text.length;
  1314. }
  1315. begin = TranslatePosition(begin);
  1316. end = TranslatePosition(end);
  1317. return { "begin": begin, "end": end };
  1318. }
  1319. }
  1320. function TranslatePosition(pos) {
  1321. if (isRTL && typeof pos == 'number' && (!opts.greedy || opts.placeholder != "")) {
  1322. var bffrLght = el.value.length;
  1323. pos = bffrLght - pos;
  1324. }
  1325. return pos;
  1326. }
  1327. function determineActiveMask(eventType, elmasks) {
  1328. if (eventType != "multiMaskScope") {
  1329. var lpc = -1, cp = -1, lvp = -1;;
  1330. $.each(elmasks, function (ndx, lmsk) {
  1331. var data = $(lmsk).data('_inputmask');
  1332. var maskset = data["maskset"];
  1333. var lastValidPosition = -1, validPositionCount = 0, caretPos = mcaret(lmsk).begin;
  1334. for (var posNdx in maskset["validPositions"]) {
  1335. var psNdx = parseInt(posNdx);
  1336. if (psNdx > lastValidPosition) lastValidPosition = psNdx;
  1337. validPositionCount++;
  1338. }
  1339. if (validPositionCount > lpc
  1340. || (validPositionCount == lpc && cp > caretPos && lvp > lastValidPosition)
  1341. || (validPositionCount == lpc && cp == caretPos && lvp < lastValidPosition)
  1342. ) {
  1343. //console.log("lvp " + lastValidPosition + " vpc " + validPositionCount + " caret " + caretPos + " ams " + ndx);
  1344. lpc = validPositionCount;
  1345. cp = caretPos;
  1346. activeMasksetIndex = ndx;
  1347. lvp = lastValidPosition;
  1348. }
  1349. });
  1350. if ($.isFunction(opts.determineActiveMasksetIndex)) activeMasksetIndex = opts.determineActiveMasksetIndex.call($el, eventType, elmasks);
  1351. var data = $el.data('_inputmask-multi') || { "activeMasksetIndex": 0, "elmasks": elmasks };
  1352. data["activeMasksetIndex"] = activeMasksetIndex;
  1353. $el.data('_inputmask-multi', data);
  1354. }
  1355. if (["focus"].indexOf(eventType) == -1 && el.value != elmasks[activeMasksetIndex]._valueGet()) {
  1356. var value = $(elmasks[activeMasksetIndex]).val() == "" ? elmasks[activeMasksetIndex]._valueGet() : $(elmasks[activeMasksetIndex]).val();
  1357. el.value = value;
  1358. }
  1359. if (["blur", "focus"].indexOf(eventType) == -1) {
  1360. if ($(elmasks[activeMasksetIndex]).hasClass("focus.inputmask")) {
  1361. var activeCaret = mcaret(elmasks[activeMasksetIndex]);
  1362. mcaret(el, activeCaret.begin, activeCaret.end);
  1363. }
  1364. }
  1365. }
  1366. opts.multi = true;
  1367. var $el = $(el), isRTL = el.dir == "rtl" || opts.numericInput;
  1368. var activeMasksetIndex = 0,
  1369. elmasks = $.map(masksets, function (msk, ndx) {
  1370. var elMaskStr = '<input type="text" ';
  1371. if ($el.attr("value")) elMaskStr += 'value="' + $el.attr("value") + '" ';
  1372. if ($el.attr("dir")) elMaskStr += 'dir="' + $el.attr("dir") + '" ';
  1373. elMaskStr += '/>';
  1374. var elmask = $(elMaskStr)[0];
  1375. maskScope($.extend(true, {}, msk), opts, { "action": "mask", "el": elmask });
  1376. return elmask;
  1377. });
  1378. $el.data('_inputmask-multi', { "activeMasksetIndex": 0, "elmasks": elmasks });
  1379. if (el.dir == "rtl" || (opts.numericInput && opts.rightAlignNumerics) || (opts.isNumeric && opts.rightAlignNumerics))
  1380. $el.css("text-align", "right");
  1381. el.dir = "ltr";
  1382. $el.removeAttr("dir");
  1383. if ($el.attr("value") != "") {
  1384. determineActiveMask("init", elmasks);
  1385. }
  1386. $el.bind("mouseenter blur focus mouseleave click dblclick keydown keypress keypress", function (e) {
  1387. var caretPos = mcaret(el), k, goDetermine = true;
  1388. if (e.type == "keydown") {
  1389. k = e.keyCode;
  1390. if (k == opts.keyCode.DOWN && activeMasksetIndex < elmasks.length - 1) {
  1391. activeMasksetIndex++;
  1392. determineActiveMask("multiMaskScope", elmasks);
  1393. return false;
  1394. } else if (k == opts.keyCode.UP && activeMasksetIndex > 0) {
  1395. activeMasksetIndex--;
  1396. determineActiveMask("multiMaskScope", elmasks);
  1397. return false;
  1398. } if (e.ctrlKey || e.shiftKey || e.altKey) {
  1399. return true;
  1400. }
  1401. } else if (e.type == "keypress" && (e.ctrlKey || e.shiftKey || e.altKey)) {
  1402. return true;
  1403. }
  1404. $.each(elmasks, function (ndx, lmnt) {
  1405. if (e.type == "keydown") {
  1406. k = e.keyCode;
  1407. if (k == opts.keyCode.BACKSPACE && lmnt._valueGet().length < caretPos.begin) {
  1408. return;
  1409. } else if (k == opts.keyCode.TAB) {
  1410. goDetermine = false;
  1411. } else if (k == opts.keyCode.RIGHT) {
  1412. mcaret(lmnt, caretPos.begin + 1, caretPos.end + 1);
  1413. goDetermine = false;
  1414. return;
  1415. } else if (k == opts.keyCode.LEFT) {
  1416. mcaret(lmnt, caretPos.begin - 1, caretPos.end - 1);
  1417. goDetermine = false;
  1418. return;
  1419. }
  1420. }
  1421. if (["click"].indexOf(e.type) != -1) {
  1422. mcaret(lmnt, TranslatePosition(caretPos.begin), TranslatePosition(caretPos.end));
  1423. if (caretPos.begin != caretPos.end) {
  1424. goDetermine = false;
  1425. return;
  1426. }
  1427. }
  1428. if (["keydown"].indexOf(e.type) != -1 && caretPos.begin != caretPos.end) {
  1429. mcaret(lmnt, caretPos.begin, caretPos.end);
  1430. }
  1431. $(lmnt).triggerHandler(e);
  1432. });
  1433. if (goDetermine) {
  1434. setTimeout(function () {
  1435. determineActiveMask(e.type, elmasks);
  1436. }, 0);
  1437. }
  1438. });
  1439. $el.bind(PasteEventType + " dragdrop drop setvalue", function (e) {
  1440. var caretPos = mcaret(el);
  1441. setTimeout(function () {
  1442. $.each(elmasks, function (ndx, lmnt) {
  1443. lmnt._valueSet(el.value);
  1444. $(lmnt).triggerHandler(e);
  1445. });
  1446. setTimeout(function () {
  1447. determineActiveMask(e.type, elmasks);
  1448. }, 0);
  1449. }, 0);
  1450. });
  1451. PatchValhookMulti(el.type);
  1452. };
  1453. $.inputmask = {
  1454. //options default
  1455. defaults: {
  1456. placeholder: "_",
  1457. optionalmarker: { start: "[", end: "]" },
  1458. quantifiermarker: { start: "{", end: "}" },
  1459. groupmarker: { start: "(", end: ")" },
  1460. alternatormarker: "|",
  1461. escapeChar: "\\",
  1462. mask: null,
  1463. oncomplete: $.noop, //executes when the mask is complete
  1464. onincomplete: $.noop, //executes when the mask is incomplete and focus is lost
  1465. oncleared: $.noop, //executes when the mask is cleared
  1466. repeat: 0, //repetitions of the mask: * ~ forever, otherwise specify an integer
  1467. greedy: true, //true: allocated buffer for the mask and repetitions - false: allocate only if needed
  1468. autoUnmask: false, //automatically unmask when retrieving the value with $.fn.val or value if the browser supports __lookupGetter__ or getOwnPropertyDescriptor
  1469. clearMaskOnLostFocus: true,
  1470. insertMode: true, //insert the input or overwrite the input
  1471. clearIncomplete: false, //clear the incomplete input on blur
  1472. aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js
  1473. onKeyUp: $.noop, //override to implement autocomplete on certain keys for example
  1474. onKeyDown: $.noop, //override to implement autocomplete on certain keys for example
  1475. onBeforeMask: undefined, //executes before masking the initial value to allow preprocessing of the initial value. args => initialValue, opts => return processedValue
  1476. onBeforePaste: undefined, //executes before masking the pasted value to allow preprocessing of the pasted value. args => pastedValue, opts => return processedValue
  1477. onUnMask: undefined, //executes after unmasking to allow postprocessing of the unmaskedvalue. args => maskedValue, unmaskedValue, opts
  1478. showMaskOnFocus: true, //show the mask-placeholder when the input has focus
  1479. showMaskOnHover: true, //show the mask-placeholder when hovering the empty input
  1480. onKeyValidation: $.noop, //executes on every key-press with the result of isValid. Params: result, opts
  1481. skipOptionalPartCharacter: " ", //a character which can be used to skip an optional part of a mask
  1482. showTooltip: false, //show the activemask as tooltip
  1483. numericInput: false, //numericInput input direction style (input shifts to the left while holding the caret position)
  1484. //numeric basic properties
  1485. isNumeric: false, //enable numeric features
  1486. radixPoint: "", //".", // | ","
  1487. skipRadixDance: false, //disable radixpoint caret positioning
  1488. rightAlignNumerics: true, //align numerics to the right
  1489. //numeric basic properties
  1490. definitions: {
  1491. '9': {
  1492. validator: "[0-9]",
  1493. cardinality: 1,
  1494. definitionSymbol: "*"
  1495. },
  1496. 'a': {
  1497. validator: "[A-Za-z\u0410-\u044F\u0401\u0451]",
  1498. cardinality: 1,
  1499. definitionSymbol: "*"
  1500. },
  1501. '*': {
  1502. validator: "[A-Za-z\u0410-\u044F\u0401\u04510-9]",
  1503. cardinality: 1
  1504. }
  1505. },
  1506. keyCode: {
  1507. 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,
  1508. 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
  1509. },
  1510. //specify keycodes which should not be considered in the keypress event, otherwise the preventDefault will stop their default behavior especially in FF
  1511. 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],
  1512. isComplete: undefined, //override for isComplete - args => buffer, opts - return true || false
  1513. //multi-masks
  1514. multi: false, //do not alter - internal use
  1515. nojumps: false, //do not jump over fixed parts in the mask
  1516. nojumpsThreshold: 0, //start nojumps as of
  1517. determineActiveMasksetIndex: undefined //override determineActiveMasksetIndex - args => eventType, elmasks - return int
  1518. },
  1519. masksCache: {},
  1520. escapeRegex: function (str) {
  1521. var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'];
  1522. return str.replace(new RegExp('(\\' + specials.join('|\\') + ')', 'gim'), '\\$1');
  1523. },
  1524. format: function (value, options) {
  1525. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  1526. resolveAlias(opts.alias, options, opts);
  1527. return maskScope(generateMaskSet(opts), opts, { "action": "format", "value": value });
  1528. },
  1529. isValid: function (value, options) {
  1530. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  1531. resolveAlias(opts.alias, options, opts);
  1532. return maskScope(generateMaskSet(opts), opts, { "action": "isValid", "value": value });
  1533. }
  1534. };
  1535. $.fn.inputmask = function (fn, options) {
  1536. function importAttributeOptions(npt, opts) {
  1537. var $npt = $(npt);
  1538. for (var option in opts) {
  1539. var optionData = $npt.data("inputmask-" + option.toLowerCase());
  1540. if (optionData != undefined)
  1541. opts[option] = optionData;
  1542. }
  1543. return opts;
  1544. }
  1545. var opts = $.extend(true, {}, $.inputmask.defaults, options),
  1546. maskset;
  1547. if (typeof fn === "string") {
  1548. switch (fn) {
  1549. case "mask":
  1550. //resolve possible aliases given by options
  1551. resolveAlias(opts.alias, options, opts);
  1552. maskset = generateMaskSet(opts);
  1553. if (maskset.length == 0) { return this; }
  1554. return this.each(function () {
  1555. if ($.isArray(maskset)) {
  1556. multiMaskScope(this, maskset, importAttributeOptions(this, opts));
  1557. } else
  1558. maskScope($.extend(true, {}, maskset), importAttributeOptions(this, opts), { "action": "mask", "el": this });
  1559. });
  1560. case "unmaskedvalue":
  1561. var $input = $(this), input = this;
  1562. if ($input.data('_inputmask')) {
  1563. maskset = $input.data('_inputmask')['maskset'];
  1564. opts = $input.data('_inputmask')['opts'];
  1565. return maskScope(maskset, opts, { "action": "unmaskedvalue", "$input": $input });
  1566. } else return $input.val();
  1567. case "remove":
  1568. return this.each(function () {
  1569. var $input = $(this), input = this;
  1570. if ($input.data('_inputmask')) {
  1571. maskset = $input.data('_inputmask')['maskset'];
  1572. opts = $input.data('_inputmask')['opts'];
  1573. //writeout the unmaskedvalue
  1574. input._valueSet(maskScope(maskset, opts, { "action": "unmaskedvalue", "$input": $input, "skipDatepickerCheck": true }));
  1575. //clear data
  1576. $input.removeData('_inputmask');
  1577. //unbind all events
  1578. $input.unbind(".inputmask");
  1579. $input.removeClass('focus.inputmask');
  1580. //restore the value property
  1581. var valueProperty;
  1582. if (Object.getOwnPropertyDescriptor)
  1583. valueProperty = Object.getOwnPropertyDescriptor(input, "value");
  1584. if (valueProperty && valueProperty.get) {
  1585. if (input._valueGet) {
  1586. Object.defineProperty(input, "value", {
  1587. get: input._valueGet,
  1588. set: input._valueSet
  1589. });
  1590. }
  1591. } else if (document.__lookupGetter__ && input.__lookupGetter__("value")) {
  1592. if (input._valueGet) {
  1593. input.__defineGetter__("value", input._valueGet);
  1594. input.__defineSetter__("value", input._valueSet);
  1595. }
  1596. }
  1597. try { //try catch needed for IE7 as it does not supports deleting fns
  1598. delete input._valueGet;
  1599. delete input._valueSet;
  1600. } catch (e) {
  1601. input._valueGet = undefined;
  1602. input._valueSet = undefined;
  1603. }
  1604. }
  1605. });
  1606. break;
  1607. case "getemptymask": //return the default (empty) mask value, usefull for setting the default value in validation
  1608. if (this.data('_inputmask')) {
  1609. maskset = this.data('_inputmask')['maskset'];
  1610. return maskset['_buffer'].join('');
  1611. }
  1612. else return "";
  1613. case "hasMaskedValue": //check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value
  1614. return this.data('_inputmask') ? !this.data('_inputmask')['opts'].autoUnmask : false;
  1615. case "isComplete":
  1616. if (this.data('_inputmask')) {
  1617. maskset = this.data('_inputmask')['maskset'];
  1618. opts = this.data('_inputmask')['opts'];
  1619. return maskScope(maskset, opts, { "action": "isComplete", "buffer": this[0]._valueGet().split(''), "el": this });
  1620. } else return true;
  1621. case "getmetadata": //return mask metadata if exists
  1622. if (this.data('_inputmask')) {
  1623. maskset = this.data('_inputmask')['maskset'];
  1624. return maskset['metadata'];
  1625. }
  1626. else return undefined;
  1627. default:
  1628. //check if the fn is an alias
  1629. if (!resolveAlias(fn, options, opts)) {
  1630. //maybe fn is a mask so we try
  1631. //set mask
  1632. opts.mask = fn;
  1633. }
  1634. maskset = generateMaskSet(opts);
  1635. if (maskset == undefined) { return this; }
  1636. return this.each(function () {
  1637. if ($.isArray(maskset)) {
  1638. multiMaskScope(this, maskset, importAttributeOptions(this, opts));
  1639. } else
  1640. maskScope($.extend(true, {}, maskset), importAttributeOptions(this, opts), { "action": "mask", "el": this });
  1641. });
  1642. break;
  1643. }
  1644. } else if (typeof fn == "object") {
  1645. opts = $.extend(true, {}, $.inputmask.defaults, fn);
  1646. resolveAlias(opts.alias, fn, opts); //resolve aliases
  1647. maskset = generateMaskSet(opts);
  1648. if (maskset == undefined) { return this; }
  1649. return this.each(function () {
  1650. if ($.isArray(maskset)) {
  1651. multiMaskScope(this, maskset, importAttributeOptions(this, opts));
  1652. } else
  1653. maskScope($.extend(true, {}, maskset), importAttributeOptions(this, opts), { "action": "mask", "el": this });
  1654. });
  1655. } else if (fn == undefined) {
  1656. //look for data-inputmask atribute - the attribute should only contain optipns
  1657. return this.each(function () {
  1658. var attrOptions = $(this).attr("data-inputmask");
  1659. if (attrOptions && attrOptions != "") {
  1660. try {
  1661. attrOptions = attrOptions.replace(new RegExp("'", "g"), '"');
  1662. var dataoptions = $.parseJSON("{" + attrOptions + "}");
  1663. $.extend(true, dataoptions, options);
  1664. opts = $.extend(true, {}, $.inputmask.defaults, dataoptions);
  1665. resolveAlias(opts.alias, dataoptions, opts);
  1666. opts.alias = undefined;
  1667. $(this).inputmask(opts);
  1668. } catch (ex) { } //need a more relax parseJSON
  1669. }
  1670. });
  1671. }
  1672. };
  1673. }
  1674. })(jQuery);
  1675. /*
  1676. Input Mask plugin extensions
  1677. http://github.com/RobinHerbots/jquery.inputmask
  1678. Copyright (c) 2010 - 2014 Robin Herbots
  1679. Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
  1680. Version: 3.0.3
  1681. Optional extensions on the jquery.inputmask base
  1682. */
  1683. (function ($) {
  1684. //extra definitions
  1685. $.extend($.inputmask.defaults.definitions, {
  1686. 'A': {
  1687. validator: "[A-Za-z]",
  1688. cardinality: 1,
  1689. casing: "upper" //auto uppercasing
  1690. },
  1691. '#': {
  1692. validator: "[A-Za-z\u0410-\u044F\u0401\u04510-9]",
  1693. cardinality: 1,
  1694. casing: "upper"
  1695. }
  1696. });
  1697. $.extend($.inputmask.defaults.aliases, {
  1698. 'url': {
  1699. mask: "ir",
  1700. placeholder: "",
  1701. separator: "",
  1702. defaultPrefix: "http://",
  1703. regex: {
  1704. urlpre1: new RegExp("[fh]"),
  1705. urlpre2: new RegExp("(ft|ht)"),
  1706. urlpre3: new RegExp("(ftp|htt)"),
  1707. urlpre4: new RegExp("(ftp:|http|ftps)"),
  1708. urlpre5: new RegExp("(ftp:/|ftps:|http:|https)"),
  1709. urlpre6: new RegExp("(ftp://|ftps:/|http:/|https:)"),
  1710. urlpre7: new RegExp("(ftp://|ftps://|http://|https:/)"),
  1711. urlpre8: new RegExp("(ftp://|ftps://|http://|https://)")
  1712. },
  1713. definitions: {
  1714. 'i': {
  1715. validator: function (chrs, buffer, pos, strict, opts) {
  1716. return true;
  1717. },
  1718. cardinality: 8,
  1719. prevalidator: (function () {
  1720. var result = [], prefixLimit = 8;
  1721. for (var i = 0; i < prefixLimit; i++) {
  1722. result[i] = (function () {
  1723. var j = i;
  1724. return {
  1725. validator: function (chrs, buffer, pos, strict, opts) {
  1726. if (opts.regex["urlpre" + (j + 1)]) {
  1727. var tmp = chrs, k;
  1728. if (((j + 1) - chrs.length) > 0) {
  1729. tmp = buffer.join('').substring(0, ((j + 1) - chrs.length)) + "" + tmp;
  1730. }
  1731. var isValid = opts.regex["urlpre" + (j + 1)].test(tmp);
  1732. if (!strict && !isValid) {
  1733. pos = pos - j;
  1734. for (k = 0; k < opts.defaultPrefix.length; k++) {
  1735. buffer[pos] = opts.defaultPrefix[k]; pos++;
  1736. }
  1737. for (k = 0; k < tmp.length - 1; k++) {
  1738. buffer[pos] = tmp[k]; pos++;
  1739. }
  1740. return { "pos": pos };
  1741. }
  1742. return isValid;
  1743. } else {
  1744. return false;
  1745. }
  1746. }, cardinality: j
  1747. };
  1748. })();
  1749. }
  1750. return result;
  1751. })()
  1752. },
  1753. "r": {
  1754. validator: ".",
  1755. cardinality: 50
  1756. }
  1757. },
  1758. insertMode: false,
  1759. autoUnmask: false
  1760. },
  1761. "ip": { //ip-address mask
  1762. mask: "i[i[i]].i[i[i]].i[i[i]].i[i[i]]",
  1763. definitions: {
  1764. 'i': {
  1765. validator: function (chrs, buffer, pos, strict, opts) {
  1766. if (pos - 1 > -1 && buffer[pos - 1] != ".") {
  1767. chrs = buffer[pos - 1] + chrs;
  1768. if (pos - 2 > -1 && buffer[pos - 2] != ".") {
  1769. chrs = buffer[pos - 2] + chrs;
  1770. } else chrs = "0" + chrs;
  1771. } else chrs = "00" + chrs;
  1772. return new RegExp("25[0-5]|2[0-4][0-9]|[01][0-9][0-9]").test(chrs);
  1773. },
  1774. cardinality: 1
  1775. }
  1776. }
  1777. },
  1778. "email": {
  1779. mask: "*{1,20}[.*{1,20}][.*{1,20}][.*{1,20}]@*{1,20}.*{2,6}[.*{1,2}]",
  1780. greedy: false
  1781. }
  1782. });
  1783. })(jQuery);
  1784. /*
  1785. Input Mask plugin extensions
  1786. http://github.com/RobinHerbots/jquery.inputmask
  1787. Copyright (c) 2010 - 2014 Robin Herbots
  1788. Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
  1789. Version: 3.0.3
  1790. Optional extensions on the jquery.inputmask base
  1791. */
  1792. (function ($) {
  1793. //date & time aliases
  1794. $.extend($.inputmask.defaults.definitions, {
  1795. 'h': { //hours
  1796. validator: "[01][0-9]|2[0-3]",
  1797. cardinality: 2,
  1798. prevalidator: [{ validator: "[0-2]", cardinality: 1 }]
  1799. },
  1800. 's': { //seconds || minutes
  1801. validator: "[0-5][0-9]",
  1802. cardinality: 2,
  1803. prevalidator: [{ validator: "[0-5]", cardinality: 1 }]
  1804. },
  1805. 'd': { //basic day
  1806. validator: "0[1-9]|[12][0-9]|3[01]",
  1807. cardinality: 2,
  1808. prevalidator: [{ validator: "[0-3]", cardinality: 1 }]
  1809. },
  1810. 'm': { //basic month
  1811. validator: "0[1-9]|1[012]",
  1812. cardinality: 2,
  1813. prevalidator: [{ validator: "[01]", cardinality: 1 }]
  1814. },
  1815. 'y': { //basic year
  1816. validator: "(19|20)\\d{2}",
  1817. cardinality: 4,
  1818. prevalidator: [
  1819. { validator: "[12]", cardinality: 1 },
  1820. { validator: "(19|20)", cardinality: 2 },
  1821. { validator: "(19|20)\\d", cardinality: 3 }
  1822. ]
  1823. }
  1824. });
  1825. $.extend($.inputmask.defaults.aliases, {
  1826. 'dd/mm/yyyy': {
  1827. mask: "1/2/y",
  1828. placeholder: "dd/mm/yyyy",
  1829. regex: {
  1830. val1pre: new RegExp("[0-3]"), //daypre
  1831. val1: new RegExp("0[1-9]|[12][0-9]|3[01]"), //day
  1832. val2pre: function (separator) { var escapedSeparator = $.inputmask.escapeRegex.call(this, separator); return new RegExp("((0[1-9]|[12][0-9]|3[01])" + escapedSeparator + "[01])"); }, //monthpre
  1833. val2: function (separator) { var escapedSeparator = $.inputmask.escapeRegex.call(this, separator); return new RegExp("((0[1-9]|[12][0-9])" + escapedSeparator + "(0[1-9]|1[012]))|(30" + escapedSeparator + "(0[13-9]|1[012]))|(31" + escapedSeparator + "(0[13578]|1[02]))"); }//month
  1834. },
  1835. leapday: "29/02/",
  1836. separator: '/',
  1837. yearrange: { minyear: 1900, maxyear: 2099 },
  1838. isInYearRange: function (chrs, minyear, maxyear) {
  1839. if (isNaN(chrs)) return false;
  1840. var enteredyear = parseInt(chrs.concat(minyear.toString().slice(chrs.length)));
  1841. var enteredyear2 = parseInt(chrs.concat(maxyear.toString().slice(chrs.length)));
  1842. return (!isNaN(enteredyear) ? minyear <= enteredyear && enteredyear <= maxyear : false) ||
  1843. (!isNaN(enteredyear2) ? minyear <= enteredyear2 && enteredyear2 <= maxyear : false);
  1844. },
  1845. determinebaseyear: function (minyear, maxyear, hint) {
  1846. var currentyear = (new Date()).getFullYear();
  1847. if (minyear > currentyear) return minyear;
  1848. if (maxyear < currentyear) {
  1849. var maxYearPrefix = maxyear.toString().slice(0, 2);
  1850. var maxYearPostfix = maxyear.toString().slice(2, 4);
  1851. while (maxyear < maxYearPrefix + hint) {
  1852. maxYearPrefix--;
  1853. }
  1854. var maxxYear = maxYearPrefix + maxYearPostfix;
  1855. return minyear > maxxYear ? minyear : maxxYear;
  1856. }
  1857. return currentyear;
  1858. },
  1859. onKeyUp: function (e, buffer, opts) {
  1860. var $input = $(this);
  1861. if (e.ctrlKey && e.keyCode == opts.keyCode.RIGHT) {
  1862. var today = new Date();
  1863. $input.val(today.getDate().toString() + (today.getMonth() + 1).toString() + today.getFullYear().toString());
  1864. }
  1865. },
  1866. definitions: {
  1867. '1': { //val1 ~ day or month
  1868. validator: function (chrs, buffer, pos, strict, opts) {
  1869. var isValid = opts.regex.val1.test(chrs);
  1870. if (!strict && !isValid) {
  1871. if (chrs.charAt(1) == opts.separator || "-./".indexOf(chrs.charAt(1)) != -1) {
  1872. isValid = opts.regex.val1.test("0" + chrs.charAt(0));
  1873. if (isValid) {
  1874. buffer[pos - 1] = "0";
  1875. return { "refreshFromBuffer": { start: pos - 1, end: pos }, "pos": pos, "c": chrs.charAt(0) };
  1876. }
  1877. }
  1878. }
  1879. return isValid;
  1880. },
  1881. cardinality: 2,
  1882. prevalidator: [{
  1883. validator: function (chrs, buffer, pos, strict, opts) {
  1884. if (!isNaN(buffer[pos + 1])) chrs += buffer[pos + 1];
  1885. var isValid = chrs.length == 1 ? opts.regex.val1pre.test(chrs) : opts.regex.val1.test(chrs);
  1886. if (!strict && !isValid) {
  1887. isValid = opts.regex.val1.test("0" + chrs);
  1888. if (isValid) {
  1889. buffer[pos] = "0";
  1890. pos++;
  1891. return { "pos": pos };
  1892. }
  1893. }
  1894. return isValid;
  1895. }, cardinality: 1
  1896. }]
  1897. },
  1898. '2': { //val2 ~ day or month
  1899. validator: function (chrs, buffer, pos, strict, opts) {
  1900. var frontValue = (opts.mask.indexOf("2") == opts.mask.length - 1) ? buffer.join('').substr(5, 3) : buffer.join('').substr(0, 3);
  1901. if (frontValue.indexOf(opts.placeholder[0]) != -1) frontValue = "01" + opts.separator;
  1902. var isValid = opts.regex.val2(opts.separator).test(frontValue + chrs);
  1903. if (!strict && !isValid) {
  1904. if (chrs.charAt(1) == opts.separator || "-./".indexOf(chrs.charAt(1)) != -1) {
  1905. isValid = opts.regex.val2(opts.separator).test(frontValue + "0" + chrs.charAt(0));
  1906. if (isValid) {
  1907. buffer[pos - 1] = "0";
  1908. return { "refreshFromBuffer": { start: pos - 1, end: pos }, "pos": pos, "c": chrs.charAt(0) };
  1909. }
  1910. }
  1911. }
  1912. //check leap yeap
  1913. if ((opts.mask.indexOf("2") == opts.mask.length - 1) && isValid) {
  1914. var dayMonthValue = buffer.join('').substr(4, 4) + chrs;
  1915. if (dayMonthValue != opts.leapday)
  1916. return true;
  1917. else {
  1918. var year = parseInt(buffer.join('').substr(0, 4), 10); //detect leap year
  1919. if (year % 4 === 0)
  1920. if (year % 100 === 0)
  1921. if (year % 400 === 0)
  1922. return true;
  1923. else return false;
  1924. else return true;
  1925. else return false;
  1926. }
  1927. }
  1928. return isValid;
  1929. },
  1930. cardinality: 2,
  1931. prevalidator: [{
  1932. validator: function (chrs, buffer, pos, strict, opts) {
  1933. if (!isNaN(buffer[pos + 1])) chrs += buffer[pos + 1];
  1934. var frontValue = (opts.mask.indexOf("2") == opts.mask.length - 1) ? buffer.join('').substr(5, 3) : buffer.join('').substr(0, 3);
  1935. if (frontValue.indexOf(opts.placeholder[0]) != -1) frontValue = "01" + opts.separator;
  1936. var isValid = chrs.length == 1 ? opts.regex.val2pre(opts.separator).test(frontValue + chrs) : opts.regex.val2(opts.separator).test(frontValue + chrs);
  1937. if (!strict && !isValid) {
  1938. isValid = opts.regex.val2(opts.separator).test(frontValue + "0" + chrs);
  1939. if (isValid) {
  1940. buffer[pos] = "0";
  1941. pos++;
  1942. return { "pos": pos };
  1943. }
  1944. }
  1945. return isValid;
  1946. }, cardinality: 1
  1947. }]
  1948. },
  1949. 'y': { //year
  1950. validator: function (chrs, buffer, pos, strict, opts) {
  1951. if (opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear)) {
  1952. var dayMonthValue = buffer.join('').substr(0, 6);
  1953. if (dayMonthValue != opts.leapday)
  1954. return true;
  1955. else {
  1956. var year = parseInt(chrs, 10);//detect leap year
  1957. if (year % 4 === 0)
  1958. if (year % 100 === 0)
  1959. if (year % 400 === 0)
  1960. return true;
  1961. else return false;
  1962. else return true;
  1963. else return false;
  1964. }
  1965. } else return false;
  1966. },
  1967. cardinality: 4,
  1968. prevalidator: [
  1969. {
  1970. validator: function (chrs, buffer, pos, strict, opts) {
  1971. var isValid = opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear);
  1972. if (!strict && !isValid) {
  1973. var yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs + "0").toString().slice(0, 1);
  1974. isValid = opts.isInYearRange(yearPrefix + chrs, opts.yearrange.minyear, opts.yearrange.maxyear);
  1975. if (isValid) {
  1976. buffer[pos++] = yearPrefix[0];
  1977. return { "pos": pos };
  1978. }
  1979. yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs + "0").toString().slice(0, 2);
  1980. isValid = opts.isInYearRange(yearPrefix + chrs, opts.yearrange.minyear, opts.yearrange.maxyear);
  1981. if (isValid) {
  1982. buffer[pos++] = yearPrefix[0];
  1983. buffer[pos++] = yearPrefix[1];
  1984. return { "pos": pos };
  1985. }
  1986. }
  1987. return isValid;
  1988. },
  1989. cardinality: 1
  1990. },
  1991. {
  1992. validator: function (chrs, buffer, pos, strict, opts) {
  1993. var isValid = opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear);
  1994. if (!strict && !isValid) {
  1995. var yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs).toString().slice(0, 2);
  1996. isValid = opts.isInYearRange(chrs[0] + yearPrefix[1] + chrs[1], opts.yearrange.minyear, opts.yearrange.maxyear);
  1997. if (isValid) {
  1998. buffer[pos++] = yearPrefix[1];
  1999. return { "pos": pos };
  2000. }
  2001. yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs).toString().slice(0, 2);
  2002. if (opts.isInYearRange(yearPrefix + chrs, opts.yearrange.minyear, opts.yearrange.maxyear)) {
  2003. var dayMonthValue = buffer.join('').substr(0, 6);
  2004. if (dayMonthValue != opts.leapday)
  2005. isValid = true;
  2006. else {
  2007. var year = parseInt(chrs, 10);//detect leap year
  2008. if (year % 4 === 0)
  2009. if (year % 100 === 0)
  2010. if (year % 400 === 0)
  2011. isValid = true;
  2012. else isValid = false;
  2013. else isValid = true;
  2014. else isValid = false;
  2015. }
  2016. } else isValid = false;
  2017. if (isValid) {
  2018. buffer[pos - 1] = yearPrefix[0];
  2019. buffer[pos++] = yearPrefix[1];
  2020. buffer[pos++] = chrs[0];
  2021. return { "refreshFromBuffer": { start: pos - 3, end: pos }, "pos": pos };
  2022. }
  2023. }
  2024. return isValid;
  2025. }, cardinality: 2
  2026. },
  2027. {
  2028. validator: function (chrs, buffer, pos, strict, opts) {
  2029. return opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear);
  2030. }, cardinality: 3
  2031. }
  2032. ]
  2033. }
  2034. },
  2035. insertMode: false,
  2036. autoUnmask: false
  2037. },
  2038. 'mm/dd/yyyy': {
  2039. placeholder: "mm/dd/yyyy",
  2040. alias: "dd/mm/yyyy", //reuse functionality of dd/mm/yyyy alias
  2041. regex: {
  2042. val2pre: function (separator) { var escapedSeparator = $.inputmask.escapeRegex.call(this, separator); return new RegExp("((0[13-9]|1[012])" + escapedSeparator + "[0-3])|(02" + escapedSeparator + "[0-2])"); }, //daypre
  2043. val2: function (separator) { var escapedSeparator = $.inputmask.escapeRegex.call(this, separator); return new RegExp("((0[1-9]|1[012])" + escapedSeparator + "(0[1-9]|[12][0-9]))|((0[13-9]|1[012])" + escapedSeparator + "30)|((0[13578]|1[02])" + escapedSeparator + "31)"); }, //day
  2044. val1pre: new RegExp("[01]"), //monthpre
  2045. val1: new RegExp("0[1-9]|1[012]") //month
  2046. },
  2047. leapday: "02/29/",
  2048. onKeyUp: function (e, buffer, opts) {
  2049. var $input = $(this);
  2050. if (e.ctrlKey && e.keyCode == opts.keyCode.RIGHT) {
  2051. var today = new Date();
  2052. $input.val((today.getMonth() + 1).toString() + today.getDate().toString() + today.getFullYear().toString());
  2053. }
  2054. }
  2055. },
  2056. 'yyyy/mm/dd': {
  2057. mask: "y/1/2",
  2058. placeholder: "yyyy/mm/dd",
  2059. alias: "mm/dd/yyyy",
  2060. leapday: "/02/29",
  2061. onKeyUp: function (e, buffer, opts) {
  2062. var $input = $(this);
  2063. if (e.ctrlKey && e.keyCode == opts.keyCode.RIGHT) {
  2064. var today = new Date();
  2065. $input.val(today.getFullYear().toString() + (today.getMonth() + 1).toString() + today.getDate().toString());
  2066. }
  2067. }
  2068. },
  2069. 'dd.mm.yyyy': {
  2070. mask: "1.2.y",
  2071. placeholder: "dd.mm.yyyy",
  2072. leapday: "29.02.",
  2073. separator: '.',
  2074. alias: "dd/mm/yyyy"
  2075. },
  2076. 'dd-mm-yyyy': {
  2077. mask: "1-2-y",
  2078. placeholder: "dd-mm-yyyy",
  2079. leapday: "29-02-",
  2080. separator: '-',
  2081. alias: "dd/mm/yyyy"
  2082. },
  2083. 'mm.dd.yyyy': {
  2084. mask: "1.2.y",
  2085. placeholder: "mm.dd.yyyy",
  2086. leapday: "02.29.",
  2087. separator: '.',
  2088. alias: "mm/dd/yyyy"
  2089. },
  2090. 'mm-dd-yyyy': {
  2091. mask: "1-2-y",
  2092. placeholder: "mm-dd-yyyy",
  2093. leapday: "02-29-",
  2094. separator: '-',
  2095. alias: "mm/dd/yyyy"
  2096. },
  2097. 'yyyy.mm.dd': {
  2098. mask: "y.1.2",
  2099. placeholder: "yyyy.mm.dd",
  2100. leapday: ".02.29",
  2101. separator: '.',
  2102. alias: "yyyy/mm/dd"
  2103. },
  2104. 'yyyy-mm-dd': {
  2105. mask: "y-1-2",
  2106. placeholder: "yyyy-mm-dd",
  2107. leapday: "-02-29",
  2108. separator: '-',
  2109. alias: "yyyy/mm/dd"
  2110. },
  2111. 'datetime': {
  2112. mask: "1/2/y h:s",
  2113. placeholder: "dd/mm/yyyy hh:mm",
  2114. alias: "dd/mm/yyyy",
  2115. regex: {
  2116. hrspre: new RegExp("[012]"), //hours pre
  2117. hrs24: new RegExp("2[0-4]|1[3-9]"),
  2118. hrs: new RegExp("[01][0-9]|2[0-4]"), //hours
  2119. ampm: new RegExp("^[a|p|A|P][m|M]")
  2120. },
  2121. timeseparator: ':',
  2122. hourFormat: "24", // or 12
  2123. definitions: {
  2124. 'h': { //hours
  2125. validator: function (chrs, buffer, pos, strict, opts) {
  2126. if (opts.hourFormat == "24") {
  2127. if (parseInt(chrs, 10) == 24) {
  2128. buffer[pos - 1] = "0";
  2129. buffer[pos] = "0";
  2130. return { "refreshFromBuffer": { start: pos - 1, end: pos }, "c": "0" };
  2131. }
  2132. }
  2133. var isValid = opts.regex.hrs.test(chrs);
  2134. if (!strict && !isValid) {
  2135. if (chrs.charAt(1) == opts.timeseparator || "-.:".indexOf(chrs.charAt(1)) != -1) {
  2136. isValid = opts.regex.hrs.test("0" + chrs.charAt(0));
  2137. if (isValid) {
  2138. buffer[pos - 1] = "0";
  2139. buffer[pos] = chrs.charAt(0);
  2140. pos++;
  2141. return { "refreshFromBuffer": { start: pos - 2, end: pos }, "pos": pos, "c": opts.timeseparator };
  2142. }
  2143. }
  2144. }
  2145. if (isValid && opts.hourFormat !== "24" && opts.regex.hrs24.test(chrs)) {
  2146. var tmp = parseInt(chrs, 10);
  2147. if (tmp == 24) {
  2148. buffer[pos + 5] = "a";
  2149. buffer[pos + 6] = "m";
  2150. } else {
  2151. buffer[pos + 5] = "p";
  2152. buffer[pos + 6] = "m";
  2153. }
  2154. tmp = tmp - 12;
  2155. if (tmp < 10) {
  2156. buffer[pos] = tmp.toString();
  2157. buffer[pos - 1] = "0";
  2158. } else {
  2159. buffer[pos] = tmp.toString().charAt(1);
  2160. buffer[pos - 1] = tmp.toString().charAt(0);
  2161. }
  2162. return { "refreshFromBuffer": { start: pos - 1, end: pos + 6 }, "c": buffer[pos] };
  2163. }
  2164. return isValid;
  2165. },
  2166. cardinality: 2,
  2167. prevalidator: [{
  2168. validator: function (chrs, buffer, pos, strict, opts) {
  2169. var isValid = opts.regex.hrspre.test(chrs);
  2170. if (!strict && !isValid) {
  2171. isValid = opts.regex.hrs.test("0" + chrs);
  2172. if (isValid) {
  2173. buffer[pos] = "0";
  2174. pos++;
  2175. return { "pos": pos };
  2176. }
  2177. }
  2178. return isValid;
  2179. }, cardinality: 1
  2180. }]
  2181. },
  2182. 't': { //am/pm
  2183. validator: function (chrs, buffer, pos, strict, opts) {
  2184. return opts.regex.ampm.test(chrs + "m");
  2185. },
  2186. casing: "lower",
  2187. cardinality: 1
  2188. }
  2189. },
  2190. insertMode: false,
  2191. autoUnmask: false
  2192. },
  2193. 'datetime12': {
  2194. mask: "1/2/y h:s t\\m",
  2195. placeholder: "dd/mm/yyyy hh:mm xm",
  2196. alias: "datetime",
  2197. hourFormat: "12"
  2198. },
  2199. 'hh:mm t': {
  2200. mask: "h:s t\\m",
  2201. placeholder: "hh:mm xm",
  2202. alias: "datetime",
  2203. hourFormat: "12"
  2204. },
  2205. 'h:s t': {
  2206. mask: "h:s t\\m",
  2207. placeholder: "hh:mm xm",
  2208. alias: "datetime",
  2209. hourFormat: "12"
  2210. },
  2211. 'hh:mm:ss': {
  2212. mask: "h:s:s",
  2213. autoUnmask: false
  2214. },
  2215. 'hh:mm': {
  2216. mask: "h:s",
  2217. autoUnmask: false
  2218. },
  2219. 'date': {
  2220. alias: "dd/mm/yyyy" // "mm/dd/yyyy"
  2221. },
  2222. 'mm/yyyy': {
  2223. mask: "1/y",
  2224. placeholder: "mm/yyyy",
  2225. leapday: "donotuse",
  2226. separator: '/',
  2227. alias: "mm/dd/yyyy"
  2228. }
  2229. });
  2230. })(jQuery);
  2231. /*
  2232. Input Mask plugin extensions
  2233. http://github.com/RobinHerbots/jquery.inputmask
  2234. Copyright (c) 2010 - 2014 Robin Herbots
  2235. Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
  2236. Version: 3.0.3
  2237. Optional extensions on the jquery.inputmask base
  2238. */
  2239. (function ($) {
  2240. //number aliases
  2241. $.extend($.inputmask.defaults.aliases, {
  2242. 'decimal': {
  2243. mask: "~",
  2244. placeholder: "",
  2245. repeat: "*",
  2246. greedy: false,
  2247. numericInput: false,
  2248. isNumeric: true,
  2249. digits: "*", //number of fractionalDigits
  2250. groupSeparator: "",//",", // | "."
  2251. radixPoint: ".",
  2252. groupSize: 3,
  2253. autoGroup: false,
  2254. allowPlus: true,
  2255. allowMinus: true,
  2256. //todo
  2257. integerDigits: "*", //number of integerDigits
  2258. defaultValue: "",
  2259. prefix: "",
  2260. suffix: "",
  2261. postFormat: function (buffer, pos, reformatOnly, opts) {
  2262. if (opts.groupSeparator == "") return pos;
  2263. var cbuf = buffer.slice(),
  2264. radixPos = $.inArray(opts.radixPoint, buffer);
  2265. if (!reformatOnly) {
  2266. cbuf.splice(pos, 0, "?"); //set position indicator
  2267. }
  2268. var bufVal = cbuf.join('');
  2269. if (opts.autoGroup || (reformatOnly && bufVal.indexOf(opts.groupSeparator) != -1)) {
  2270. var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator);
  2271. bufVal = bufVal.replace(new RegExp(escapedGroupSeparator, "g"), '');
  2272. var radixSplit = bufVal.split(opts.radixPoint);
  2273. bufVal = radixSplit[0];
  2274. var reg = new RegExp('([-\+]?[\\d\?]+)([\\d\?]{' + opts.groupSize + '})');
  2275. while (reg.test(bufVal)) {
  2276. bufVal = bufVal.replace(reg, '$1' + opts.groupSeparator + '$2');
  2277. bufVal = bufVal.replace(opts.groupSeparator + opts.groupSeparator, opts.groupSeparator);
  2278. }
  2279. if (radixSplit.length > 1)
  2280. bufVal += opts.radixPoint + radixSplit[1];
  2281. }
  2282. buffer.length = bufVal.length; //align the length
  2283. for (var i = 0, l = bufVal.length; i < l; i++) {
  2284. buffer[i] = bufVal.charAt(i);
  2285. }
  2286. var newPos = $.inArray("?", buffer);
  2287. if (!reformatOnly) buffer.splice(newPos, 1);
  2288. return reformatOnly ? pos : newPos;
  2289. },
  2290. regex: {
  2291. number: function (opts) {
  2292. var escapedRadixPoint = $.inputmask.escapeRegex.call(this, opts.radixPoint);
  2293. var digitExpression = isNaN(opts.digits) ? opts.digits : '{0,' + opts.digits + '}';
  2294. var integerExpression = isNaN(opts.integerDigits) ? opts.integerDigits : '{1,' + opts.integerDigits + '}';
  2295. var signedExpression = opts.allowPlus || opts.allowMinus ? "[" + (opts.allowPlus ? "\+" : "") + (opts.allowMinus ? "-" : "") + "]?" : "";
  2296. var currentRegExp = "^" + signedExpression + "\\d" + integerExpression + "(" + escapedRadixPoint + "\\d" + digitExpression + ")?$";
  2297. return new RegExp(currentRegExp);
  2298. }
  2299. },
  2300. onKeyDown: function (e, buffer, opts) {
  2301. var $input = $(this), input = this;
  2302. if (e.keyCode == opts.keyCode.TAB) {
  2303. var radixPosition = $.inArray(opts.radixPoint, buffer);
  2304. if (radixPosition != -1) {
  2305. var masksets = $input.data('_inputmask')['masksets'];
  2306. var activeMasksetIndex = $input.data('_inputmask')['activeMasksetIndex'];
  2307. for (var i = 1; i <= opts.digits && i < opts.getMaskLength(masksets[activeMasksetIndex]["_buffer"], opts.greedy, opts.repeat, buffer, opts) ; i++) {
  2308. if (buffer[radixPosition + i] == undefined || buffer[radixPosition + i] == "") buffer[radixPosition + i] = "0";
  2309. }
  2310. return { "refreshFromBuffer": true };
  2311. }
  2312. } else if (e.keyCode == opts.keyCode.DELETE || e.keyCode == opts.keyCode.BACKSPACE) {
  2313. opts.postFormat(buffer, 0, true, opts);
  2314. input._valueSet(buffer.join(''));
  2315. return { "refreshFromBuffer": true };
  2316. }
  2317. },
  2318. definitions: {
  2319. '~': { //real number
  2320. validator: function (chrs, buffer, pos, strict, opts) {
  2321. var iopts = $.extend({}, opts, { digits: strict ? "*" : opts.digits });
  2322. if (chrs == "") return false;
  2323. if (!strict && pos <= 1 && buffer[0] === '0' && new RegExp("[\\d-]").test(chrs) && buffer.join('').length == 1) { //handle first char
  2324. buffer[0] = "";
  2325. return { "pos": 0 };
  2326. }
  2327. var cbuf = strict ? buffer.slice(0, pos) : buffer.slice();
  2328. cbuf.splice(pos, 0, chrs);
  2329. var bufferStr = cbuf.join('');
  2330. //strip groupseparator
  2331. var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator);
  2332. bufferStr = bufferStr.replace(new RegExp(escapedGroupSeparator, "g"), '');
  2333. if (strict && bufferStr.lastIndexOf(opts.radixPoint) == bufferStr.length - 1) {
  2334. var escapedRadixPoint = $.inputmask.escapeRegex.call(this, opts.radixPoint);
  2335. bufferStr = bufferStr.replace(new RegExp(escapedRadixPoint, "g"), '');
  2336. }
  2337. if (!strict && bufferStr == "") return false;
  2338. var isValid = opts.regex.number(iopts).test(bufferStr);
  2339. if (!isValid) {
  2340. //let's help the regex a bit
  2341. bufferStr += "0";
  2342. isValid = opts.regex.number(iopts).test(bufferStr);
  2343. if (!isValid) {
  2344. //make a valid group
  2345. var lastGroupSeparator = bufferStr.lastIndexOf(opts.groupSeparator);
  2346. for (var i = bufferStr.length - lastGroupSeparator; i <= 3; i++) {
  2347. bufferStr += "0";
  2348. }
  2349. isValid = opts.regex.number(iopts).test(bufferStr);
  2350. if (!isValid && !strict) {
  2351. if (chrs == opts.radixPoint) {
  2352. isValid = opts.regex.number(iopts).test("0" + bufferStr + "0");
  2353. if (isValid) {
  2354. buffer[pos] = "0";
  2355. pos++;
  2356. return { "pos": pos };
  2357. }
  2358. }
  2359. }
  2360. }
  2361. }
  2362. if (isValid != false && !strict && chrs != opts.radixPoint) {
  2363. var newPos = opts.postFormat(buffer, pos, (chrs == "-" || chrs == "+") ? true : false, opts);
  2364. return { "pos": newPos, "refreshFromBuffer": true };
  2365. }
  2366. return isValid;
  2367. },
  2368. cardinality: 1,
  2369. prevalidator: null
  2370. }
  2371. },
  2372. insertMode: true,
  2373. autoUnmask: false
  2374. },
  2375. 'integer': {
  2376. regex: {
  2377. number: function (opts) {
  2378. var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator);
  2379. var signedExpression = opts.allowPlus || opts.allowMinus ? "[" + (opts.allowPlus ? "\+" : "") + (opts.allowMinus ? "-" : "") + "]?" : "";
  2380. return new RegExp("^" + signedExpression + "(\\d+|\\d{1," + opts.groupSize + "}((" + escapedGroupSeparator + "\\d{" + opts.groupSize + "})?)+)$");
  2381. }
  2382. },
  2383. alias: "decimal"
  2384. }
  2385. });
  2386. })(jQuery);
  2387. /*
  2388. Input Mask plugin extensions
  2389. http://github.com/RobinHerbots/jquery.inputmask
  2390. Copyright (c) 2010 - 2014 Robin Herbots
  2391. Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
  2392. Version: 3.0.3
  2393. Regex extensions on the jquery.inputmask base
  2394. Allows for using regular expressions as a mask
  2395. */
  2396. (function ($) {
  2397. $.extend($.inputmask.defaults.aliases, { // $(selector).inputmask("Regex", { regex: "[0-9]*"}
  2398. 'Regex': {
  2399. mask: "r",
  2400. greedy: false,
  2401. repeat: "*",
  2402. regex: null,
  2403. regexTokens: null,
  2404. //Thx to https://github.com/slevithan/regex-colorizer for the tokenizer regex
  2405. tokenizer: /\[\^?]?(?:[^\\\]]+|\\[\S\s]?)*]?|\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9][0-9]*|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)|\((?:\?[:=!]?)?|(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[()|\\]+|./g,
  2406. quantifierFilter: /[0-9]+[^,]/,
  2407. isComplete: function(buffer, opts){
  2408. return new RegExp(opts.regex).test(buffer.join(''));
  2409. },
  2410. definitions: {
  2411. 'r': {
  2412. validator: function (chrs, buffer, pos, strict, opts) {
  2413. function regexToken(isGroup, isQuantifier) {
  2414. this.matches = [];
  2415. this.isGroup = isGroup || false;
  2416. this.isQuantifier = isQuantifier || false;
  2417. this.quantifier = { min: 1, max: 1 };
  2418. this.repeaterPart = undefined;
  2419. }
  2420. function analyseRegex() {
  2421. var currentToken = new regexToken(), match, m, opengroups = [];
  2422. opts.regexTokens = [];
  2423. // The tokenizer regex does most of the tokenization grunt work
  2424. while (match = opts.tokenizer.exec(opts.regex)) {
  2425. m = match[0];
  2426. switch (m.charAt(0)) {
  2427. case "(": // Group opening
  2428. opengroups.push(new regexToken(true));
  2429. break;
  2430. case ")": // Group closing
  2431. var groupToken = opengroups.pop();
  2432. if (opengroups.length > 0) {
  2433. opengroups[opengroups.length - 1]["matches"].push(groupToken);
  2434. } else {
  2435. currentToken.matches.push(groupToken);
  2436. }
  2437. break;
  2438. case "{": case "+": case "*": //Quantifier
  2439. var quantifierToken = new regexToken(false, true);
  2440. m = m.replace(/[{}]/g, "");
  2441. var mq = m.split(","), mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]), mq1 = mq.length == 1 ? mq0 : (isNaN(mq[1]) ? mq[1] : parseInt(mq[1]));
  2442. quantifierToken.quantifier = { min: mq0, max: mq1 };
  2443. if (opengroups.length > 0) {
  2444. var matches = opengroups[opengroups.length - 1]["matches"];
  2445. match = matches.pop();
  2446. if (!match["isGroup"]) {
  2447. var groupToken = new regexToken(true);
  2448. groupToken.matches.push(match);
  2449. match = groupToken;
  2450. }
  2451. matches.push(match);
  2452. matches.push(quantifierToken);
  2453. } else {
  2454. match = currentToken.matches.pop();
  2455. if (!match["isGroup"]) {
  2456. var groupToken = new regexToken(true);
  2457. groupToken.matches.push(match);
  2458. match = groupToken;
  2459. }
  2460. currentToken.matches.push(match);
  2461. currentToken.matches.push(quantifierToken);
  2462. }
  2463. break;
  2464. default:
  2465. if (opengroups.length > 0) {
  2466. opengroups[opengroups.length - 1]["matches"].push(m);
  2467. } else {
  2468. currentToken.matches.push(m);
  2469. }
  2470. break;
  2471. }
  2472. }
  2473. if (currentToken.matches.length > 0)
  2474. opts.regexTokens.push(currentToken);
  2475. };
  2476. function validateRegexToken(token, fromGroup) {
  2477. var isvalid = false;
  2478. if (fromGroup) {
  2479. regexPart += "(";
  2480. openGroupCount++;
  2481. }
  2482. for (var mndx = 0; mndx < token["matches"].length; mndx++) {
  2483. var matchToken = token["matches"][mndx];
  2484. if (matchToken["isGroup"] == true) {
  2485. isvalid = validateRegexToken(matchToken, true);
  2486. } else if (matchToken["isQuantifier"] == true) {
  2487. var crrntndx = token["matches"].indexOf(matchToken),
  2488. matchGroup = token["matches"][crrntndx - 1];
  2489. var regexPartBak = regexPart;
  2490. if (isNaN(matchToken.quantifier.max)) {
  2491. while (matchToken["repeaterPart"] && matchToken["repeaterPart"] != regexPart && matchToken["repeaterPart"].length > regexPart.length) {
  2492. isvalid = validateRegexToken(matchGroup, true);
  2493. if (isvalid) break;
  2494. }
  2495. isvalid = isvalid || validateRegexToken(matchGroup, true);
  2496. if (isvalid) matchToken["repeaterPart"] = regexPart;
  2497. regexPart = regexPartBak + matchToken.quantifier.max;
  2498. } else {
  2499. for (var i = 0, qm = matchToken.quantifier.max - 1; i < qm; i++) {
  2500. isvalid = validateRegexToken(matchGroup, true);
  2501. if (isvalid) break;
  2502. }
  2503. regexPart = regexPartBak + "{" + matchToken.quantifier.min + "," + matchToken.quantifier.max + "}";
  2504. }
  2505. } else if (matchToken["matches"] != undefined) {
  2506. for (var k = 0; k < matchToken.length; k++) {
  2507. isvalid = validateRegexToken(matchToken[k], fromGroup);
  2508. if (isvalid) break;
  2509. }
  2510. } else {
  2511. var testExp;
  2512. if (matchToken[0] == "[") {
  2513. testExp = regexPart;
  2514. testExp += matchToken;
  2515. for (var j = 0; j < openGroupCount; j++) {
  2516. testExp += ")";
  2517. }
  2518. var exp = new RegExp("^(" + testExp + ")$");
  2519. isvalid = exp.test(bufferStr);
  2520. } else {
  2521. for (var l = 0, tl = matchToken.length; l < tl; l++) {
  2522. if (matchToken[l] == "\\") continue;
  2523. testExp = regexPart;
  2524. testExp += matchToken.substr(0, l + 1);
  2525. testExp = testExp.replace(/\|$/, "");
  2526. for (var j = 0; j < openGroupCount; j++) {
  2527. testExp += ")";
  2528. }
  2529. var exp = new RegExp("^(" + testExp + ")$");
  2530. isvalid = exp.test(bufferStr);
  2531. if (isvalid) break;
  2532. }
  2533. }
  2534. regexPart += matchToken;
  2535. }
  2536. if (isvalid) break;
  2537. }
  2538. if (fromGroup) {
  2539. regexPart += ")";
  2540. openGroupCount--;
  2541. }
  2542. return isvalid;
  2543. }
  2544. if (opts.regexTokens == null) {
  2545. analyseRegex();
  2546. }
  2547. var cbuffer = buffer.slice(), regexPart = "", isValid = false, openGroupCount = 0;
  2548. cbuffer.splice(pos, 0, chrs);
  2549. var bufferStr = cbuffer.join('');
  2550. for (var i = 0; i < opts.regexTokens.length; i++) {
  2551. var regexToken = opts.regexTokens[i];
  2552. isValid = validateRegexToken(regexToken, regexToken["isGroup"]);
  2553. if (isValid) break;
  2554. }
  2555. return isValid;
  2556. },
  2557. cardinality: 1
  2558. }
  2559. }
  2560. }
  2561. });
  2562. })(jQuery);
  2563. /*
  2564. Input Mask plugin extensions
  2565. http://github.com/RobinHerbots/jquery.inputmask
  2566. Copyright (c) 2010 - 2014 Robin Herbots
  2567. Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
  2568. Version: 3.0.3
  2569. Phone extension.
  2570. When using this extension make sure you specify the correct url to get the masks
  2571. $(selector).inputmask("phone", {
  2572. url: "Scripts/jquery.inputmask/phone-codes/phone-codes.json",
  2573. onKeyValidation: function () { //show some metadata in the console
  2574. console.log($(this).inputmask("getmetadata")["name_en"]);
  2575. }
  2576. });
  2577. */
  2578. (function ($) {
  2579. $.extend($.inputmask.defaults.aliases, {
  2580. 'phone': {
  2581. url: "phone-codes/phone-codes.json",
  2582. mask: function (opts) {
  2583. opts.definitions = {
  2584. 'p': {
  2585. validator: function () { return false; },
  2586. cardinality: 1
  2587. },
  2588. '#': {
  2589. validator: "[0-9]",
  2590. cardinality: 1
  2591. }
  2592. };
  2593. var maskList = [];
  2594. $.ajax({
  2595. url: opts.url,
  2596. async: false,
  2597. dataType: 'json',
  2598. success: function (response) {
  2599. maskList = response;
  2600. }
  2601. });
  2602. maskList.splice(0, 0, "+p(ppp)ppp-pppp");
  2603. return maskList;
  2604. },
  2605. nojumps: true,
  2606. nojumpsThreshold: 1
  2607. },
  2608. 'phonebe': {
  2609. url: "phone-codes/phone-be.json",
  2610. mask: function (opts) {
  2611. opts.definitions = {
  2612. 'p': {
  2613. validator: function () { return false; },
  2614. cardinality: 1
  2615. },
  2616. '#': {
  2617. validator: "[0-9]",
  2618. cardinality: 1
  2619. }
  2620. };
  2621. var maskList = [];
  2622. $.ajax({
  2623. url: opts.url,
  2624. async: false,
  2625. dataType: 'json',
  2626. success: function (response) {
  2627. maskList = response;
  2628. }
  2629. });
  2630. maskList.splice(0, 0, "+32(ppp)ppp-pppp");
  2631. return maskList;
  2632. },
  2633. nojumps: true,
  2634. nojumpsThreshold: 4
  2635. }
  2636. });
  2637. })(jQuery);