jquery.inputmask.bundle.js 159 KB

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