jquery.inputmask.bundle.js 147 KB

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