jquery.inputmask.bundle.js 144 KB

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