jquery.inputmask.bundle.js 145 KB

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