jquery.inputmask.bundle.js 144 KB

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