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