jquery.inputmask.bundle.js 142 KB

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