jquery.inputmask.bundle.js 143 KB

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