jquery.inputmask.bundle.js 148 KB

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