jquery.inputmask.bundle.js 146 KB

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