jquery.inputmask.bundle.js 142 KB

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