jquery.inputmask.bundle.js 144 KB

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