jquery.inputmask.bundle.js 148 KB

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