jquery.inputmask.bundle.js 142 KB

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