jquery.inputmask.bundle.js 143 KB

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