jquery.inputmask.bundle.js 144 KB

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