jquery.inputmask.js 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632
  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: 0.0.0
  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 generateMaskSets(opts) {
  33. var ms = [];
  34. var genmasks = []; //used to keep track of the masks that where processed, to avoid duplicates
  35. function getMaskTemplate(mask) {
  36. if (opts.numericInput) {
  37. mask = mask.split('').reverse().join('');
  38. }
  39. var escaped = false, outCount = 0, greedy = opts.greedy, repeat = opts.repeat;
  40. if (repeat == "*") greedy = false;
  41. //if (greedy == true && opts.placeholder == "") opts.placeholder = " ";
  42. if (mask.length == 1 && greedy == false && repeat != 0) { opts.placeholder = ""; } //hide placeholder with single non-greedy mask
  43. var singleMask = $.map(mask.split(""), function (element, index) {
  44. var outElem = [];
  45. if (element == opts.escapeChar) {
  46. escaped = true;
  47. }
  48. else if ((element != opts.optionalmarker.start && element != opts.optionalmarker.end) || escaped) {
  49. var maskdef = opts.definitions[element];
  50. if (maskdef && !escaped) {
  51. for (var i = 0; i < maskdef.cardinality; i++) {
  52. outElem.push(opts.placeholder.charAt((outCount + i) % opts.placeholder.length));
  53. }
  54. } else {
  55. outElem.push(element);
  56. escaped = false;
  57. }
  58. outCount += outElem.length;
  59. return outElem;
  60. }
  61. });
  62. //allocate repetitions
  63. var repeatedMask = singleMask.slice();
  64. for (var i = 1; i < repeat && greedy; i++) {
  65. repeatedMask = repeatedMask.concat(singleMask.slice());
  66. }
  67. return { "mask": repeatedMask, "repeat": repeat, "greedy": greedy };
  68. }
  69. //test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, offset: int, casing: null/upper/lower, def: definitionSymbol}
  70. function getTestingChain(mask) {
  71. if (opts.numericInput) {
  72. mask = mask.split('').reverse().join('');
  73. }
  74. var isOptional = false, escaped = false;
  75. var newBlockMarker = false; //indicates wheter the begin/ending of a block should be indicated
  76. return $.map(mask.split(""), function (element, index) {
  77. var outElem = [];
  78. if (element == opts.escapeChar) {
  79. escaped = true;
  80. } else if (element == opts.optionalmarker.start && !escaped) {
  81. isOptional = true;
  82. newBlockMarker = true;
  83. }
  84. else if (element == opts.optionalmarker.end && !escaped) {
  85. isOptional = false;
  86. newBlockMarker = true;
  87. }
  88. else {
  89. var maskdef = opts.definitions[element];
  90. if (maskdef && !escaped) {
  91. var prevalidators = maskdef["prevalidator"], prevalidatorsL = prevalidators ? prevalidators.length : 0;
  92. for (var i = 1; i < maskdef.cardinality; i++) {
  93. var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [], validator = prevalidator["validator"], cardinality = prevalidator["cardinality"];
  94. outElem.push({ fn: validator ? typeof validator == 'string' ? new RegExp(validator) : new function () { this.test = validator; } : new RegExp("."), cardinality: cardinality ? cardinality : 1, optionality: isOptional, newBlockMarker: isOptional == true ? newBlockMarker : false, offset: 0, casing: maskdef["casing"], def: maskdef["definitionSymbol"] || element });
  95. if (isOptional == true) //reset newBlockMarker
  96. newBlockMarker = false;
  97. }
  98. outElem.push({ fn: maskdef.validator ? typeof maskdef.validator == 'string' ? new RegExp(maskdef.validator) : new function () { this.test = maskdef.validator; } : new RegExp("."), cardinality: maskdef.cardinality, optionality: isOptional, newBlockMarker: newBlockMarker, offset: 0, casing: maskdef["casing"], def: maskdef["definitionSymbol"] || element });
  99. } else {
  100. outElem.push({ fn: null, cardinality: 0, optionality: isOptional, newBlockMarker: newBlockMarker, offset: 0, casing: null, def: element });
  101. escaped = false;
  102. }
  103. //reset newBlockMarker
  104. newBlockMarker = false;
  105. return outElem;
  106. }
  107. });
  108. }
  109. function markOptional(maskPart) { //needed for the clearOptionalTail functionality
  110. return opts.optionalmarker.start + maskPart + opts.optionalmarker.end;
  111. }
  112. function splitFirstOptionalEndPart(maskPart) {
  113. var optionalStartMarkers = 0, optionalEndMarkers = 0, mpl = maskPart.length;
  114. for (var i = 0; i < mpl; i++) {
  115. if (maskPart.charAt(i) == opts.optionalmarker.start) {
  116. optionalStartMarkers++;
  117. }
  118. if (maskPart.charAt(i) == opts.optionalmarker.end) {
  119. optionalEndMarkers++;
  120. }
  121. if (optionalStartMarkers > 0 && optionalStartMarkers == optionalEndMarkers)
  122. break;
  123. }
  124. var maskParts = [maskPart.substring(0, i)];
  125. if (i < mpl) {
  126. maskParts.push(maskPart.substring(i + 1, mpl));
  127. }
  128. return maskParts;
  129. }
  130. function splitFirstOptionalStartPart(maskPart) {
  131. var mpl = maskPart.length;
  132. for (var i = 0; i < mpl; i++) {
  133. if (maskPart.charAt(i) == opts.optionalmarker.start) {
  134. break;
  135. }
  136. }
  137. var maskParts = [maskPart.substring(0, i)];
  138. if (i < mpl) {
  139. maskParts.push(maskPart.substring(i + 1, mpl));
  140. }
  141. return maskParts;
  142. }
  143. function generateMask(maskPrefix, maskPart, metadata) {
  144. var maskParts = splitFirstOptionalEndPart(maskPart);
  145. var newMask, maskTemplate;
  146. var masks = splitFirstOptionalStartPart(maskParts[0]);
  147. if (masks.length > 1) {
  148. newMask = maskPrefix + masks[0] + markOptional(masks[1]) + (maskParts.length > 1 ? maskParts[1] : "");
  149. if ($.inArray(newMask, genmasks) == -1 && newMask != "") {
  150. genmasks.push(newMask);
  151. maskTemplate = getMaskTemplate(newMask);
  152. ms.push({
  153. "mask": newMask,
  154. "_buffer": maskTemplate["mask"],
  155. "buffer": maskTemplate["mask"].slice(),
  156. "tests": getTestingChain(newMask),
  157. "lastValidPosition": -1,
  158. "greedy": maskTemplate["greedy"],
  159. "repeat": maskTemplate["repeat"],
  160. "metadata": metadata
  161. });
  162. }
  163. newMask = maskPrefix + masks[0] + (maskParts.length > 1 ? maskParts[1] : "");
  164. if ($.inArray(newMask, genmasks) == -1 && newMask != "") {
  165. genmasks.push(newMask);
  166. maskTemplate = getMaskTemplate(newMask);
  167. ms.push({
  168. "mask": newMask,
  169. "_buffer": maskTemplate["mask"],
  170. "buffer": maskTemplate["mask"].slice(),
  171. "tests": getTestingChain(newMask),
  172. "lastValidPosition": -1,
  173. "greedy": maskTemplate["greedy"],
  174. "repeat": maskTemplate["repeat"],
  175. "metadata": metadata
  176. });
  177. }
  178. if (splitFirstOptionalStartPart(masks[1]).length > 1) { //optional contains another optional
  179. generateMask(maskPrefix + masks[0], masks[1] + maskParts[1], metadata);
  180. }
  181. if (maskParts.length > 1 && splitFirstOptionalStartPart(maskParts[1]).length > 1) {
  182. generateMask(maskPrefix + masks[0] + markOptional(masks[1]), maskParts[1], metadata);
  183. generateMask(maskPrefix + masks[0], maskParts[1], metadata);
  184. }
  185. }
  186. else {
  187. newMask = maskPrefix + maskParts;
  188. if ($.inArray(newMask, genmasks) == -1 && newMask != "") {
  189. genmasks.push(newMask);
  190. maskTemplate = getMaskTemplate(newMask);
  191. ms.push({
  192. "mask": newMask,
  193. "_buffer": maskTemplate["mask"],
  194. "buffer": maskTemplate["mask"].slice(),
  195. "tests": getTestingChain(newMask),
  196. "lastValidPosition": -1,
  197. "greedy": maskTemplate["greedy"],
  198. "repeat": maskTemplate["repeat"],
  199. "metadata": metadata
  200. });
  201. }
  202. }
  203. }
  204. if ($.isFunction(opts.mask)) { //allow mask to be a preprocessing fn - should return a valid mask
  205. opts.mask = opts.mask.call(this, opts);
  206. }
  207. if ($.isArray(opts.mask)) {
  208. $.each(opts.mask, function (ndx, msk) {
  209. if (msk["mask"] != undefined) {
  210. generateMask("", msk["mask"].toString(), msk);
  211. } else
  212. generateMask("", msk.toString());
  213. });
  214. } else generateMask("", opts.mask.toString());
  215. return opts.greedy ? ms : ms.sort(function (a, b) { return a["mask"].length - b["mask"].length; });
  216. }
  217. var msie10 = navigator.userAgent.match(new RegExp("msie 10", "i")) !== null,
  218. iphone = navigator.userAgent.match(new RegExp("iphone", "i")) !== null,
  219. android = navigator.userAgent.match(new RegExp("android.*safari.*", "i")) !== null,
  220. androidchrome = navigator.userAgent.match(new RegExp("android.*chrome.*", "i")) !== null,
  221. pasteEvent = isInputEventSupported('paste') ? 'paste' : isInputEventSupported('input') ? 'input' : "propertychange";
  222. //masking scope
  223. //actionObj definition see below
  224. function maskScope(masksets, activeMasksetIndex, opts, actionObj) {
  225. var isRTL = false,
  226. valueOnFocus = getActiveBuffer().join(''),
  227. $el, chromeValueOnInput,
  228. skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
  229. skipInputEvent = false, //skip when triggered from within inputmask
  230. ignorable = false;
  231. //maskset helperfunctions
  232. function getActiveMaskSet() {
  233. return masksets[activeMasksetIndex];
  234. }
  235. function getActiveTests() {
  236. return getActiveMaskSet()['tests'];
  237. }
  238. function getActiveBufferTemplate() {
  239. return getActiveMaskSet()['_buffer'];
  240. }
  241. function getActiveBuffer() {
  242. return getActiveMaskSet()['buffer'];
  243. }
  244. function isValid(pos, c, strict) { //strict true ~ no correction or autofill
  245. strict = strict === true; //always set a value to strict to prevent possible strange behavior in the extensions
  246. function _isValid(position, activeMaskset, c, strict) {
  247. var testPos = determineTestPosition(position), loopend = c ? 1 : 0, chrs = '', buffer = activeMaskset["buffer"];
  248. for (var i = activeMaskset['tests'][testPos].cardinality; i > loopend; i--) {
  249. chrs += getBufferElement(buffer, testPos - (i - 1));
  250. }
  251. if (c) {
  252. chrs += c;
  253. }
  254. //return is false or a json object => { pos: ??, c: ??} or true
  255. return activeMaskset['tests'][testPos].fn != null ?
  256. activeMaskset['tests'][testPos].fn.test(chrs, buffer, position, strict, opts)
  257. : (c == getBufferElement(activeMaskset['_buffer'], position, true) || c == opts.skipOptionalPartCharacter) ?
  258. { "refresh": true, c: getBufferElement(activeMaskset['_buffer'], position, true), pos: position }
  259. : false;
  260. }
  261. function PostProcessResults(maskForwards, results) {
  262. var hasValidActual = false;
  263. $.each(results, function (ndx, rslt) {
  264. hasValidActual = $.inArray(rslt["activeMasksetIndex"], maskForwards) == -1 && rslt["result"] !== false;
  265. if (hasValidActual) return false;
  266. });
  267. if (hasValidActual) { //strip maskforwards
  268. results = $.map(results, function (rslt, ndx) {
  269. if ($.inArray(rslt["activeMasksetIndex"], maskForwards) == -1) {
  270. return rslt;
  271. } else {
  272. masksets[rslt["activeMasksetIndex"]]["lastValidPosition"] = actualLVP;
  273. }
  274. });
  275. } else { //keep maskforwards with the least forward
  276. var lowestPos = -1, lowestIndex = -1, rsltValid;
  277. $.each(results, function (ndx, rslt) {
  278. if ($.inArray(rslt["activeMasksetIndex"], maskForwards) != -1 && rslt["result"] !== false & (lowestPos == -1 || lowestPos > rslt["result"]["pos"])) {
  279. lowestPos = rslt["result"]["pos"];
  280. lowestIndex = rslt["activeMasksetIndex"];
  281. }
  282. });
  283. results = $.map(results, function (rslt, ndx) {
  284. if ($.inArray(rslt["activeMasksetIndex"], maskForwards) != -1) {
  285. if (rslt["result"]["pos"] == lowestPos) {
  286. return rslt;
  287. } else if (rslt["result"] !== false) {
  288. for (var i = pos; i < lowestPos; i++) {
  289. rsltValid = _isValid(i, masksets[rslt["activeMasksetIndex"]], masksets[lowestIndex]["buffer"][i], true);
  290. if (rsltValid === false) {
  291. masksets[rslt["activeMasksetIndex"]]["lastValidPosition"] = lowestPos - 1;
  292. break;
  293. } else {
  294. setBufferElement(masksets[rslt["activeMasksetIndex"]]["buffer"], i, masksets[lowestIndex]["buffer"][i], true);
  295. masksets[rslt["activeMasksetIndex"]]["lastValidPosition"] = i;
  296. }
  297. }
  298. //also check check for the lowestpos with the new input
  299. rsltValid = _isValid(lowestPos, masksets[rslt["activeMasksetIndex"]], c, true);
  300. if (rsltValid !== false) {
  301. setBufferElement(masksets[rslt["activeMasksetIndex"]]["buffer"], lowestPos, c, true);
  302. masksets[rslt["activeMasksetIndex"]]["lastValidPosition"] = lowestPos;
  303. }
  304. //console.log("ndx " + rslt["activeMasksetIndex"] + " validate " + masksets[rslt["activeMasksetIndex"]]["buffer"].join('') + " lv " + masksets[rslt["activeMasksetIndex"]]['lastValidPosition']);
  305. return rslt;
  306. }
  307. }
  308. });
  309. }
  310. return results;
  311. }
  312. if (strict) {
  313. var result = _isValid(pos, getActiveMaskSet(), c, strict); //only check validity in current mask when validating strict
  314. if (result === true) {
  315. result = { "pos": pos }; //always take a possible corrected maskposition into account
  316. }
  317. return result;
  318. }
  319. var results = [], result = false, currentActiveMasksetIndex = activeMasksetIndex,
  320. actualBuffer = getActiveBuffer().slice(), actualLVP = getActiveMaskSet()["lastValidPosition"],
  321. actualPrevious = seekPrevious(pos),
  322. maskForwards = [];
  323. $.each(masksets, function (index, value) {
  324. if (typeof (value) == "object") {
  325. activeMasksetIndex = index;
  326. var maskPos = pos;
  327. var lvp = getActiveMaskSet()['lastValidPosition'],
  328. rsltValid;
  329. if (lvp == actualLVP) {
  330. if ((maskPos - actualLVP) > 1) {
  331. for (var i = lvp == -1 ? 0 : lvp; i < maskPos; i++) {
  332. rsltValid = _isValid(i, getActiveMaskSet(), actualBuffer[i], true);
  333. if (rsltValid === false) {
  334. break;
  335. } else {
  336. setBufferElement(getActiveBuffer(), i, actualBuffer[i], true);
  337. if (rsltValid === true) {
  338. rsltValid = { "pos": i }; //always take a possible corrected maskposition into account
  339. }
  340. var newValidPosition = rsltValid.pos || i;
  341. if (getActiveMaskSet()['lastValidPosition'] < newValidPosition)
  342. getActiveMaskSet()['lastValidPosition'] = newValidPosition; //set new position from isValid
  343. }
  344. }
  345. }
  346. //does the input match on a further position?
  347. if (!isMask(maskPos) && !_isValid(maskPos, getActiveMaskSet(), c, strict)) {
  348. var maxForward = seekNext(maskPos) - maskPos;
  349. for (var fw = 0; fw < maxForward; fw++) {
  350. if (_isValid(++maskPos, getActiveMaskSet(), c, strict) !== false)
  351. break;
  352. }
  353. maskForwards.push(activeMasksetIndex);
  354. //console.log('maskforward ' + activeMasksetIndex + " pos " + pos + " maskPos " + maskPos);
  355. }
  356. }
  357. if (getActiveMaskSet()['lastValidPosition'] >= actualLVP || activeMasksetIndex == currentActiveMasksetIndex) {
  358. if (maskPos >= 0 && maskPos < getMaskLength()) {
  359. result = _isValid(maskPos, getActiveMaskSet(), c, strict);
  360. if (result !== false) {
  361. if (result === true) {
  362. result = { "pos": maskPos }; //always take a possible corrected maskposition into account
  363. }
  364. var newValidPosition = result.pos || maskPos;
  365. if (getActiveMaskSet()['lastValidPosition'] < newValidPosition)
  366. getActiveMaskSet()['lastValidPosition'] = newValidPosition; //set new position from isValid
  367. }
  368. //console.log("pos " + pos + " ndx " + activeMasksetIndex + " validate " + getActiveBuffer().join('') + " lv " + getActiveMaskSet()['lastValidPosition']);
  369. results.push({ "activeMasksetIndex": index, "result": result });
  370. }
  371. }
  372. }
  373. });
  374. activeMasksetIndex = currentActiveMasksetIndex; //reset activeMasksetIndex
  375. return PostProcessResults(maskForwards, results); //return results of the multiple mask validations
  376. }
  377. function determineActiveMasksetIndex() {
  378. var currentMasksetIndex = activeMasksetIndex,
  379. highestValid = { "activeMasksetIndex": 0, "lastValidPosition": -1, "next": -1 };
  380. $.each(masksets, function (index, value) {
  381. if (typeof (value) == "object") {
  382. activeMasksetIndex = index;
  383. if (getActiveMaskSet()['lastValidPosition'] > highestValid['lastValidPosition']) {
  384. highestValid["activeMasksetIndex"] = index;
  385. highestValid["lastValidPosition"] = getActiveMaskSet()['lastValidPosition'];
  386. highestValid["next"] = seekNext(getActiveMaskSet()['lastValidPosition']);
  387. } else if (getActiveMaskSet()['lastValidPosition'] == highestValid['lastValidPosition'] &&
  388. (highestValid['next'] == -1 || highestValid['next'] > seekNext(getActiveMaskSet()['lastValidPosition']))) {
  389. highestValid["activeMasksetIndex"] = index;
  390. highestValid["lastValidPosition"] = getActiveMaskSet()['lastValidPosition'];
  391. highestValid["next"] = seekNext(getActiveMaskSet()['lastValidPosition']);
  392. }
  393. }
  394. });
  395. activeMasksetIndex = highestValid["lastValidPosition"] != -1 && masksets[currentMasksetIndex]["lastValidPosition"] == highestValid["lastValidPosition"] ? currentMasksetIndex : highestValid["activeMasksetIndex"];
  396. if (currentMasksetIndex != activeMasksetIndex) {
  397. clearBuffer(getActiveBuffer(), seekNext(highestValid["lastValidPosition"]), getMaskLength());
  398. getActiveMaskSet()["writeOutBuffer"] = true;
  399. }
  400. $el.data('_inputmask')['activeMasksetIndex'] = activeMasksetIndex; //store the activeMasksetIndex
  401. }
  402. function isMask(pos) {
  403. var testPos = determineTestPosition(pos);
  404. var test = getActiveTests()[testPos];
  405. return test != undefined ? test.fn : false;
  406. }
  407. function determineTestPosition(pos) {
  408. return pos % getActiveTests().length;
  409. }
  410. function getMaskLength() {
  411. return opts.getMaskLength(getActiveBufferTemplate(), getActiveMaskSet()['greedy'], getActiveMaskSet()['repeat'], getActiveBuffer(), opts);
  412. }
  413. //pos: from position
  414. function seekNext(pos) {
  415. var maskL = getMaskLength();
  416. if (pos >= maskL) return maskL;
  417. var position = pos;
  418. while (++position < maskL && !isMask(position)) {
  419. }
  420. return position;
  421. }
  422. //pos: from position
  423. function seekPrevious(pos) {
  424. var position = pos;
  425. if (position <= 0) return 0;
  426. while (--position > 0 && !isMask(position)) {
  427. }
  428. ;
  429. return position;
  430. }
  431. function setBufferElement(buffer, position, element, autoPrepare) {
  432. if (autoPrepare) position = prepareBuffer(buffer, position);
  433. var test = getActiveTests()[determineTestPosition(position)];
  434. var elem = element;
  435. if (elem != undefined && test != undefined) {
  436. switch (test.casing) {
  437. case "upper":
  438. elem = element.toUpperCase();
  439. break;
  440. case "lower":
  441. elem = element.toLowerCase();
  442. break;
  443. }
  444. }
  445. buffer[position] = elem;
  446. }
  447. function getBufferElement(buffer, position, autoPrepare) {
  448. if (autoPrepare) position = prepareBuffer(buffer, position);
  449. return buffer[position];
  450. }
  451. //needed to handle the non-greedy mask repetitions
  452. function prepareBuffer(buffer, position) {
  453. var j;
  454. while (buffer[position] == undefined && buffer.length < getMaskLength()) {
  455. j = 0;
  456. while (getActiveBufferTemplate()[j] !== undefined) { //add a new buffer
  457. buffer.push(getActiveBufferTemplate()[j++]);
  458. }
  459. }
  460. return position;
  461. }
  462. function writeBuffer(input, buffer, caretPos) {
  463. input._valueSet(buffer.join(''));
  464. if (caretPos != undefined) {
  465. caret(input, caretPos);
  466. }
  467. }
  468. function clearBuffer(buffer, start, end, stripNomasks) {
  469. for (var i = start, maskL = getMaskLength() ; i < end && i < maskL; i++) {
  470. if (stripNomasks === true) {
  471. if (!isMask(i))
  472. setBufferElement(buffer, i, "");
  473. } else
  474. setBufferElement(buffer, i, getBufferElement(getActiveBufferTemplate().slice(), i, true));
  475. }
  476. }
  477. function setReTargetPlaceHolder(buffer, pos) {
  478. var testPos = determineTestPosition(pos);
  479. setBufferElement(buffer, pos, getBufferElement(getActiveBufferTemplate(), testPos));
  480. }
  481. function getPlaceHolder(pos) {
  482. return opts.placeholder.charAt(pos % opts.placeholder.length);
  483. }
  484. function checkVal(input, writeOut, strict, nptvl, intelliCheck) {
  485. var inputValue = nptvl != undefined ? nptvl.slice() : truncateInput(input._valueGet()).split('');
  486. $.each(masksets, function (ndx, ms) {
  487. if (typeof (ms) == "object") {
  488. ms["buffer"] = ms["_buffer"].slice();
  489. ms["lastValidPosition"] = -1;
  490. ms["p"] = -1;
  491. }
  492. });
  493. if (strict !== true) activeMasksetIndex = 0;
  494. if (writeOut) input._valueSet(""); //initial clear
  495. var ml = getMaskLength();
  496. $.each(inputValue, function (ndx, charCode) {
  497. if (intelliCheck === true) {
  498. var p = getActiveMaskSet()["p"], lvp = p == -1 ? p : seekPrevious(p),
  499. pos = lvp == -1 ? ndx : seekNext(lvp);
  500. if ($.inArray(charCode, getActiveBufferTemplate().slice(lvp + 1, pos)) == -1) {
  501. keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), writeOut, strict, ndx);
  502. }
  503. } else {
  504. keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), writeOut, strict, ndx);
  505. }
  506. });
  507. if (strict === true && getActiveMaskSet()["p"] != -1) {
  508. getActiveMaskSet()["lastValidPosition"] = seekPrevious(getActiveMaskSet()["p"]);
  509. }
  510. }
  511. function escapeRegex(str) {
  512. return $.inputmask.escapeRegex.call(this, str);
  513. }
  514. function truncateInput(inputValue) {
  515. return inputValue.replace(new RegExp("(" + escapeRegex(getActiveBufferTemplate().join('')) + ")*$"), "");
  516. }
  517. function clearOptionalTail(input) {
  518. var buffer = getActiveBuffer(), tmpBuffer = buffer.slice(), testPos, pos;
  519. for (var pos = tmpBuffer.length - 1; pos >= 0; pos--) {
  520. var testPos = determineTestPosition(pos);
  521. if (getActiveTests()[testPos].optionality) {
  522. if (!isMask(pos) || !isValid(pos, buffer[pos], true))
  523. tmpBuffer.pop();
  524. else break;
  525. } else break;
  526. }
  527. writeBuffer(input, tmpBuffer);
  528. }
  529. function unmaskedvalue($input, skipDatepickerCheck) {
  530. if (getActiveTests() && (skipDatepickerCheck === true || !$input.hasClass('hasDatepicker'))) {
  531. //checkVal(input, false, true);
  532. var umValue = $.map(getActiveBuffer(), function (element, index) {
  533. return isMask(index) && isValid(index, element, true) ? element : null;
  534. });
  535. var unmaskedValue = (isRTL ? umValue.reverse() : umValue).join('');
  536. return opts.onUnMask != undefined ? opts.onUnMask.call(this, getActiveBuffer().join(''), unmaskedValue) : unmaskedValue;
  537. } else {
  538. return $input[0]._valueGet();
  539. }
  540. }
  541. function TranslatePosition(pos) {
  542. if (isRTL && typeof pos == 'number' && (!opts.greedy || opts.placeholder != "")) {
  543. var bffrLght = getActiveBuffer().length;
  544. pos = bffrLght - pos;
  545. }
  546. return pos;
  547. }
  548. function caret(input, begin, end) {
  549. var npt = input.jquery && input.length > 0 ? input[0] : input, range;
  550. if (typeof begin == 'number') {
  551. begin = TranslatePosition(begin);
  552. end = TranslatePosition(end);
  553. if (!$(input).is(':visible')) {
  554. return;
  555. }
  556. end = (typeof end == 'number') ? end : begin;
  557. npt.scrollLeft = npt.scrollWidth;
  558. if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode
  559. if (npt.setSelectionRange) {
  560. npt.selectionStart = begin;
  561. npt.selectionEnd = android ? begin : end;
  562. } else if (npt.createTextRange) {
  563. range = npt.createTextRange();
  564. range.collapse(true);
  565. range.moveEnd('character', end);
  566. range.moveStart('character', begin);
  567. range.select();
  568. }
  569. } else {
  570. if (!$(input).is(':visible')) {
  571. return { "begin": 0, "end": 0 };
  572. }
  573. if (npt.setSelectionRange) {
  574. begin = npt.selectionStart;
  575. end = npt.selectionEnd;
  576. } else if (document.selection && document.selection.createRange) {
  577. range = document.selection.createRange();
  578. begin = 0 - range.duplicate().moveStart('character', -100000);
  579. end = begin + range.text.length;
  580. }
  581. begin = TranslatePosition(begin);
  582. end = TranslatePosition(end);
  583. return { "begin": begin, "end": end };
  584. }
  585. }
  586. function isComplete(buffer) { //return true / false / undefined (repeat *)
  587. if (opts.repeat == "*") return undefined;
  588. var complete = false, highestValidPosition = 0, currentActiveMasksetIndex = activeMasksetIndex;
  589. $.each(masksets, function (ndx, ms) {
  590. if (typeof (ms) == "object") {
  591. activeMasksetIndex = ndx;
  592. var aml = seekPrevious(getMaskLength());
  593. if (ms["lastValidPosition"] >= highestValidPosition && ms["lastValidPosition"] == aml) {
  594. var msComplete = true;
  595. for (var i = 0; i <= aml; i++) {
  596. var mask = isMask(i), testPos = determineTestPosition(i);
  597. if ((mask && (buffer[i] == undefined || buffer[i] == getPlaceHolder(i))) || (!mask && buffer[i] != getActiveBufferTemplate()[testPos])) {
  598. msComplete = false;
  599. break;
  600. }
  601. }
  602. complete = complete || msComplete;
  603. if (complete) //break loop
  604. return false;
  605. }
  606. highestValidPosition = ms["lastValidPosition"];
  607. }
  608. });
  609. activeMasksetIndex = currentActiveMasksetIndex; //reset activeMaskset
  610. return complete;
  611. }
  612. function isSelection(begin, end) {
  613. return isRTL ? (begin - end) > 1 || ((begin - end) == 1 && opts.insertMode) :
  614. (end - begin) > 1 || ((end - begin) == 1 && opts.insertMode);
  615. }
  616. //private functions
  617. function installEventRuler(npt) {
  618. var events = $._data(npt).events;
  619. $.each(events, function (eventType, eventHandlers) {
  620. $.each(eventHandlers, function (ndx, eventHandler) {
  621. if (eventHandler.namespace == "inputmask") {
  622. if (eventHandler.type != "setvalue") {
  623. var handler = eventHandler.handler;
  624. eventHandler.handler = function (e) {
  625. if (this.readOnly || this.disabled)
  626. e.preventDefault;
  627. else
  628. return handler.apply(this, arguments);
  629. };
  630. }
  631. }
  632. });
  633. });
  634. }
  635. function patchValueProperty(npt) {
  636. var valueProperty;
  637. if (Object.getOwnPropertyDescriptor)
  638. valueProperty = Object.getOwnPropertyDescriptor(npt, "value");
  639. if (valueProperty && valueProperty.get) {
  640. if (!npt._valueGet) {
  641. var valueGet = valueProperty.get;
  642. var valueSet = valueProperty.set;
  643. npt._valueGet = function () {
  644. return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
  645. };
  646. npt._valueSet = function (value) {
  647. valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
  648. };
  649. Object.defineProperty(npt, "value", {
  650. get: function () {
  651. var $self = $(this), inputData = $(this).data('_inputmask'), masksets = inputData['masksets'],
  652. activeMasksetIndex = inputData['activeMasksetIndex'];
  653. return inputData && inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : valueGet.call(this) != masksets[activeMasksetIndex]['_buffer'].join('') ? valueGet.call(this) : '';
  654. },
  655. set: function (value) {
  656. valueSet.call(this, value);
  657. $(this).triggerHandler('setvalue.inputmask');
  658. }
  659. });
  660. }
  661. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  662. if (!npt._valueGet) {
  663. var valueGet = npt.__lookupGetter__("value");
  664. var valueSet = npt.__lookupSetter__("value");
  665. npt._valueGet = function () {
  666. return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
  667. };
  668. npt._valueSet = function (value) {
  669. valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
  670. };
  671. npt.__defineGetter__("value", function () {
  672. var $self = $(this), inputData = $(this).data('_inputmask'), masksets = inputData['masksets'],
  673. activeMasksetIndex = inputData['activeMasksetIndex'];
  674. return inputData && inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : valueGet.call(this) != masksets[activeMasksetIndex]['_buffer'].join('') ? valueGet.call(this) : '';
  675. });
  676. npt.__defineSetter__("value", function (value) {
  677. valueSet.call(this, value);
  678. $(this).triggerHandler('setvalue.inputmask');
  679. });
  680. }
  681. } else {
  682. if (!npt._valueGet) {
  683. npt._valueGet = function () { return isRTL ? this.value.split('').reverse().join('') : this.value; };
  684. npt._valueSet = function (value) { this.value = isRTL ? value.split('').reverse().join('') : value; };
  685. }
  686. if ($.valHooks.text == undefined || $.valHooks.text.inputmaskpatch != true) {
  687. var valueGet = $.valHooks.text && $.valHooks.text.get ? $.valHooks.text.get : function (elem) { return elem.value; };
  688. var valueSet = $.valHooks.text && $.valHooks.text.set ? $.valHooks.text.set : function (elem, value) {
  689. elem.value = value;
  690. return elem;
  691. };
  692. jQuery.extend($.valHooks, {
  693. text: {
  694. get: function (elem) {
  695. var $elem = $(elem);
  696. if ($elem.data('_inputmask')) {
  697. if ($elem.data('_inputmask')['opts'].autoUnmask)
  698. return $elem.inputmask('unmaskedvalue');
  699. else {
  700. var result = valueGet(elem),
  701. inputData = $elem.data('_inputmask'), masksets = inputData['masksets'],
  702. activeMasksetIndex = inputData['activeMasksetIndex'];
  703. return result != masksets[activeMasksetIndex]['_buffer'].join('') ? result : '';
  704. }
  705. } else return valueGet(elem);
  706. },
  707. set: function (elem, value) {
  708. var $elem = $(elem);
  709. var result = valueSet(elem, value);
  710. if ($elem.data('_inputmask')) $elem.triggerHandler('setvalue.inputmask');
  711. return result;
  712. },
  713. inputmaskpatch: true
  714. }
  715. });
  716. }
  717. }
  718. }
  719. //shift chars to left from start to end and put c at end position if defined
  720. function shiftL(start, end, c, maskJumps) {
  721. var buffer = getActiveBuffer();
  722. if (maskJumps !== false) //jumping over nonmask position
  723. while (!isMask(start) && start - 1 >= 0) start--;
  724. for (var i = start; i < end && i < getMaskLength() ; i++) {
  725. if (isMask(i)) {
  726. setReTargetPlaceHolder(buffer, i);
  727. var j = seekNext(i);
  728. var p = getBufferElement(buffer, j);
  729. if (p != getPlaceHolder(j)) {
  730. if (j < getMaskLength() && isValid(i, p, true) !== false && getActiveTests()[determineTestPosition(i)].def == getActiveTests()[determineTestPosition(j)].def) {
  731. setBufferElement(buffer, i, p, true);
  732. } else {
  733. if (isMask(i))
  734. break;
  735. }
  736. }
  737. } else {
  738. setReTargetPlaceHolder(buffer, i);
  739. }
  740. }
  741. if (c != undefined)
  742. setBufferElement(buffer, seekPrevious(end), c);
  743. if (getActiveMaskSet()["greedy"] == false) {
  744. var trbuffer = truncateInput(buffer.join('')).split('');
  745. buffer.length = trbuffer.length;
  746. for (var i = 0, bl = buffer.length; i < bl; i++) {
  747. buffer[i] = trbuffer[i];
  748. }
  749. if (buffer.length == 0) getActiveMaskSet()["buffer"] = getActiveBufferTemplate().slice();
  750. }
  751. return start; //return the used start position
  752. }
  753. function shiftR(start, end, c) {
  754. var buffer = getActiveBuffer();
  755. if (getBufferElement(buffer, start, true) != getPlaceHolder(start)) {
  756. for (var i = seekPrevious(end) ; i > start && i >= 0; i--) {
  757. if (isMask(i)) {
  758. var j = seekPrevious(i);
  759. var t = getBufferElement(buffer, j);
  760. if (t != getPlaceHolder(j)) {
  761. if (isValid(j, t, true) !== false && getActiveTests()[determineTestPosition(i)].def == getActiveTests()[determineTestPosition(j)].def) {
  762. setBufferElement(buffer, i, t, true);
  763. setReTargetPlaceHolder(buffer, j);
  764. } //else break;
  765. }
  766. } else
  767. setReTargetPlaceHolder(buffer, i);
  768. }
  769. }
  770. if (c != undefined && getBufferElement(buffer, start) == getPlaceHolder(start))
  771. setBufferElement(buffer, start, c);
  772. var lengthBefore = buffer.length;
  773. if (getActiveMaskSet()["greedy"] == false) {
  774. var trbuffer = truncateInput(buffer.join('')).split('');
  775. buffer.length = trbuffer.length;
  776. for (var i = 0, bl = buffer.length; i < bl; i++) {
  777. buffer[i] = trbuffer[i];
  778. }
  779. if (buffer.length == 0) getActiveMaskSet()["buffer"] = getActiveBufferTemplate().slice();
  780. }
  781. return end - (lengthBefore - buffer.length); //return new start position
  782. }
  783. ;
  784. function HandleRemove(input, k, pos) {
  785. if (opts.numericInput || isRTL) {
  786. switch (k) {
  787. case opts.keyCode.BACKSPACE:
  788. k = opts.keyCode.DELETE;
  789. break;
  790. case opts.keyCode.DELETE:
  791. k = opts.keyCode.BACKSPACE;
  792. break;
  793. }
  794. if (isRTL) {
  795. var pend = pos.end;
  796. pos.end = pos.begin;
  797. pos.begin = pend;
  798. }
  799. }
  800. var isSelection = true;
  801. if (pos.begin == pos.end) {
  802. var posBegin = k == opts.keyCode.BACKSPACE ? pos.begin - 1 : pos.begin;
  803. if (opts.isNumeric && opts.radixPoint != "" && getActiveBuffer()[posBegin] == opts.radixPoint) {
  804. pos.begin = (getActiveBuffer().length - 1 == posBegin) /* radixPoint is latest? delete it */ ? pos.begin : k == opts.keyCode.BACKSPACE ? posBegin : seekNext(posBegin);
  805. pos.end = pos.begin;
  806. }
  807. isSelection = false;
  808. if (k == opts.keyCode.BACKSPACE)
  809. pos.begin--;
  810. else if (k == opts.keyCode.DELETE)
  811. pos.end++;
  812. } else if (pos.end - pos.begin == 1 && !opts.insertMode) {
  813. isSelection = false;
  814. if (k == opts.keyCode.BACKSPACE)
  815. pos.begin--;
  816. }
  817. clearBuffer(getActiveBuffer(), pos.begin, pos.end);
  818. var ml = getMaskLength();
  819. if (opts.greedy == false) {
  820. shiftL(pos.begin, ml, undefined, !isRTL && (k == opts.keyCode.BACKSPACE && !isSelection));
  821. } else {
  822. var newpos = pos.begin;
  823. for (var i = pos.begin; i < pos.end; i++) { //seeknext to skip placeholders at start in selection
  824. if (isMask(i) || !isSelection)
  825. newpos = shiftL(pos.begin, ml, undefined, !isRTL && (k == opts.keyCode.BACKSPACE && !isSelection));
  826. }
  827. if (!isSelection) pos.begin = newpos;
  828. }
  829. var firstMaskPos = seekNext(-1);
  830. clearBuffer(getActiveBuffer(), pos.begin, pos.end, true);
  831. checkVal(input, false, masksets[1] == undefined || firstMaskPos >= pos.end, getActiveBuffer());
  832. if (getActiveMaskSet()['lastValidPosition'] < firstMaskPos) {
  833. getActiveMaskSet()["lastValidPosition"] = -1;
  834. getActiveMaskSet()["p"] = firstMaskPos;
  835. } else {
  836. getActiveMaskSet()["p"] = pos.begin;
  837. }
  838. }
  839. function keydownEvent(e) {
  840. //Safari 5.1.x - modal dialog fires keypress twice workaround
  841. skipKeyPressEvent = false;
  842. var input = this, $input = $(input), k = e.keyCode, pos = caret(input);
  843. //backspace, delete, and escape get special treatment
  844. if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iphone && k == 127) || e.ctrlKey && k == 88) { //backspace/delete
  845. e.preventDefault(); //stop default action but allow propagation
  846. if (k == 88) valueOnFocus = getActiveBuffer().join('');
  847. HandleRemove(input, k, pos);
  848. determineActiveMasksetIndex();
  849. writeBuffer(input, getActiveBuffer(), getActiveMaskSet()["p"]);
  850. if (input._valueGet() == getActiveBufferTemplate().join(''))
  851. $input.trigger('cleared');
  852. if (opts.showTooltip) { //update tooltip
  853. $input.prop("title", getActiveMaskSet()["mask"]);
  854. }
  855. } else if (k == opts.keyCode.END || k == opts.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  856. setTimeout(function () {
  857. var caretPos = seekNext(getActiveMaskSet()["lastValidPosition"]);
  858. if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--;
  859. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
  860. }, 0);
  861. } else if ((k == opts.keyCode.HOME && !e.shiftKey) || k == opts.keyCode.PAGE_UP) { //Home or page_up
  862. caret(input, 0, e.shiftKey ? pos.begin : 0);
  863. } else if (k == opts.keyCode.ESCAPE || (k == 90 && e.ctrlKey)) { //escape && undo
  864. checkVal(input, true, false, valueOnFocus.split(''));
  865. $input.click();
  866. } else if (k == opts.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
  867. opts.insertMode = !opts.insertMode;
  868. caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin);
  869. } else if (opts.insertMode == false && !e.shiftKey) {
  870. if (k == opts.keyCode.RIGHT) {
  871. setTimeout(function () {
  872. var caretPos = caret(input);
  873. caret(input, caretPos.begin);
  874. }, 0);
  875. } else if (k == opts.keyCode.LEFT) {
  876. setTimeout(function () {
  877. var caretPos = caret(input);
  878. caret(input, caretPos.begin - 1);
  879. }, 0);
  880. }
  881. }
  882. var currentCaretPos = caret(input);
  883. if (opts.onKeyDown.call(this, e, getActiveBuffer(), opts) === true) //extra stuff to execute on keydown
  884. caret(input, currentCaretPos.begin, currentCaretPos.end);
  885. ignorable = $.inArray(k, opts.ignorables) != -1;
  886. }
  887. function keypressEvent(e, checkval, k, writeOut, strict, ndx) {
  888. //Safari 5.1.x - modal dialog fires keypress twice workaround
  889. if (k == undefined && skipKeyPressEvent) return false;
  890. skipKeyPressEvent = true;
  891. var input = this, $input = $(input);
  892. e = e || window.event;
  893. var k = checkval ? k : (e.which || e.charCode || e.keyCode);
  894. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  895. return true;
  896. } else {
  897. if (k) {
  898. //special treat the decimal separator
  899. if (checkval !== true && k == 46 && e.shiftKey == false && opts.radixPoint == ",") k = 44;
  900. var pos, results, result, c = String.fromCharCode(k);
  901. if (checkval) {
  902. var pcaret = strict ? ndx : getActiveMaskSet()["lastValidPosition"] + 1;
  903. pos = { begin: pcaret, end: pcaret };
  904. } else {
  905. pos = caret(input);
  906. }
  907. //should we clear a possible selection??
  908. var isSlctn = isSelection(pos.begin, pos.end), redetermineLVP = false,
  909. initialIndex = activeMasksetIndex;
  910. if (isSlctn) {
  911. activeMasksetIndex = initialIndex;
  912. $.each(masksets, function (ndx, lmnt) { //init undobuffer for recovery when not valid
  913. if (typeof (lmnt) == "object") {
  914. activeMasksetIndex = ndx;
  915. getActiveMaskSet()["undoBuffer"] = getActiveBuffer().join('');
  916. }
  917. });
  918. HandleRemove(input, opts.keyCode.DELETE, pos);
  919. if (!opts.insertMode) { //preserve some space
  920. $.each(masksets, function (ndx, lmnt) {
  921. if (typeof (lmnt) == "object") {
  922. activeMasksetIndex = ndx;
  923. shiftR(pos.begin, getMaskLength());
  924. getActiveMaskSet()["lastValidPosition"] = seekNext(getActiveMaskSet()["lastValidPosition"]);
  925. }
  926. });
  927. }
  928. activeMasksetIndex = initialIndex; //restore index
  929. }
  930. var radixPosition = getActiveBuffer().join('').indexOf(opts.radixPoint);
  931. if (opts.isNumeric && checkval !== true && radixPosition != -1) {
  932. if (opts.greedy && pos.begin <= radixPosition) {
  933. pos.begin = seekPrevious(pos.begin);
  934. pos.end = pos.begin;
  935. } else if (c == opts.radixPoint) {
  936. pos.begin = radixPosition;
  937. pos.end = pos.begin;
  938. }
  939. }
  940. var p = pos.begin;
  941. results = isValid(p, c, strict);
  942. if (strict === true) results = [{ "activeMasksetIndex": activeMasksetIndex, "result": results }];
  943. var minimalForwardPosition = -1;
  944. $.each(results, function (index, result) {
  945. activeMasksetIndex = result["activeMasksetIndex"];
  946. getActiveMaskSet()["writeOutBuffer"] = true;
  947. var np = result["result"];
  948. if (np !== false) {
  949. var refresh = false, buffer = getActiveBuffer();
  950. if (np !== true) {
  951. refresh = np["refresh"]; //only rewrite buffer from isValid
  952. p = np.pos != undefined ? np.pos : p; //set new position from isValid
  953. c = np.c != undefined ? np.c : c; //set new char from isValid
  954. }
  955. if (refresh !== true) {
  956. if (opts.insertMode == true) {
  957. var lastUnmaskedPosition = getMaskLength();
  958. var bfrClone = buffer.slice();
  959. while (getBufferElement(bfrClone, lastUnmaskedPosition, true) != getPlaceHolder(lastUnmaskedPosition) && lastUnmaskedPosition >= p) {
  960. lastUnmaskedPosition = lastUnmaskedPosition == 0 ? -1 : seekPrevious(lastUnmaskedPosition);
  961. }
  962. if (lastUnmaskedPosition >= p) {
  963. shiftR(p, getMaskLength(), c);
  964. //shift the lvp if needed
  965. var lvp = getActiveMaskSet()["lastValidPosition"], nlvp = seekNext(lvp);
  966. if (nlvp != getMaskLength() && lvp >= p && (getBufferElement(getActiveBuffer(), nlvp, true) != getPlaceHolder(nlvp))) {
  967. getActiveMaskSet()["lastValidPosition"] = nlvp;
  968. }
  969. } else getActiveMaskSet()["writeOutBuffer"] = false;
  970. } else setBufferElement(buffer, p, c, true);
  971. if (minimalForwardPosition == -1 || minimalForwardPosition > seekNext(p)) {
  972. minimalForwardPosition = seekNext(p);
  973. }
  974. } else if (!strict) {
  975. var nextPos = p < getMaskLength() ? p + 1 : p;
  976. if (minimalForwardPosition == -1 || minimalForwardPosition > nextPos) {
  977. minimalForwardPosition = nextPos;
  978. }
  979. }
  980. if (minimalForwardPosition > getActiveMaskSet()["p"])
  981. getActiveMaskSet()["p"] = minimalForwardPosition; //needed for checkval strict
  982. }
  983. });
  984. if (strict !== true) {
  985. activeMasksetIndex = initialIndex;
  986. determineActiveMasksetIndex();
  987. }
  988. if (writeOut !== false) {
  989. $.each(results, function (ndx, rslt) {
  990. if (rslt["activeMasksetIndex"] == activeMasksetIndex) {
  991. result = rslt;
  992. return false;
  993. }
  994. });
  995. if (result != undefined) {
  996. var self = this;
  997. setTimeout(function () { opts.onKeyValidation.call(self, result["result"], opts); }, 0);
  998. if (getActiveMaskSet()["writeOutBuffer"] && result["result"] !== false) {
  999. var buffer = getActiveBuffer();
  1000. var newCaretPosition;
  1001. if (checkval) {
  1002. newCaretPosition = undefined;
  1003. } else if (opts.numericInput) {
  1004. if (p > radixPosition) {
  1005. newCaretPosition = seekPrevious(minimalForwardPosition);
  1006. } else if (c == opts.radixPoint) {
  1007. newCaretPosition = minimalForwardPosition - 1;
  1008. } else newCaretPosition = seekPrevious(minimalForwardPosition - 1);
  1009. } else {
  1010. newCaretPosition = minimalForwardPosition;
  1011. }
  1012. writeBuffer(input, buffer, newCaretPosition);
  1013. if (checkval !== true) {
  1014. setTimeout(function () { //timeout needed for IE
  1015. if (isComplete(buffer) === true)
  1016. $input.trigger("complete");
  1017. skipInputEvent = true;
  1018. $input.trigger("input");
  1019. }, 0);
  1020. }
  1021. } else if (isSlctn) {
  1022. getActiveMaskSet()["buffer"] = getActiveMaskSet()["undoBuffer"].split('');
  1023. }
  1024. }
  1025. }
  1026. if (opts.showTooltip) { //update tooltip
  1027. $input.prop("title", getActiveMaskSet()["mask"]);
  1028. }
  1029. //needed for IE8 and below
  1030. if (e) e.preventDefault ? e.preventDefault() : e.returnValue = false;
  1031. }
  1032. }
  1033. }
  1034. function keyupEvent(e) {
  1035. var $input = $(this), input = this, k = e.keyCode, buffer = getActiveBuffer();
  1036. if (androidchrome && k == opts.keyCode.BACKSPACE) {
  1037. if (chromeValueOnInput == input._valueGet())
  1038. keydownEvent.call(this, e);
  1039. }
  1040. opts.onKeyUp.call(this, e, buffer, opts); //extra stuff to execute on keyup
  1041. if (k == opts.keyCode.TAB && opts.showMaskOnFocus) {
  1042. if ($input.hasClass('focus.inputmask') && input._valueGet().length == 0) {
  1043. buffer = getActiveBufferTemplate().slice();
  1044. writeBuffer(input, buffer);
  1045. caret(input, 0);
  1046. valueOnFocus = getActiveBuffer().join('');
  1047. } else {
  1048. writeBuffer(input, buffer);
  1049. if (buffer.join('') == getActiveBufferTemplate().join('') && $.inArray(opts.radixPoint, buffer) != -1) {
  1050. caret(input, TranslatePosition(0));
  1051. $input.click();
  1052. } else
  1053. caret(input, TranslatePosition(0), TranslatePosition(getMaskLength()));
  1054. }
  1055. }
  1056. }
  1057. function inputEvent(e) {
  1058. if (skipInputEvent === true) {
  1059. skipInputEvent = false;
  1060. return true;
  1061. }
  1062. var input = this, $input = $(input);
  1063. chromeValueOnInput = getActiveBuffer().join('');
  1064. checkVal(input, false, false);
  1065. writeBuffer(input, getActiveBuffer());
  1066. if (isComplete(getActiveBuffer()) === true)
  1067. $input.trigger("complete");
  1068. $input.click();
  1069. }
  1070. function mask(el) {
  1071. $el = $(el);
  1072. if ($el.is(":input")) {
  1073. //store tests & original buffer in the input element - used to get the unmasked value
  1074. $el.data('_inputmask', {
  1075. 'masksets': masksets,
  1076. 'activeMasksetIndex': activeMasksetIndex,
  1077. 'opts': opts,
  1078. 'isRTL': false
  1079. });
  1080. //show tooltip
  1081. if (opts.showTooltip) {
  1082. $el.prop("title", getActiveMaskSet()["mask"]);
  1083. }
  1084. //correct greedy setting if needed
  1085. getActiveMaskSet()['greedy'] = getActiveMaskSet()['greedy'] ? getActiveMaskSet()['greedy'] : getActiveMaskSet()['repeat'] == 0;
  1086. //handle maxlength attribute
  1087. if ($el.attr("maxLength") != null) //only when the attribute is set
  1088. {
  1089. var maxLength = $el.prop('maxLength');
  1090. if (maxLength > -1) { //handle *-repeat
  1091. $.each(masksets, function (ndx, ms) {
  1092. if (typeof (ms) == "object") {
  1093. if (ms["repeat"] == "*") {
  1094. ms["repeat"] = maxLength;
  1095. }
  1096. }
  1097. });
  1098. }
  1099. if (getMaskLength() >= maxLength && maxLength > -1) { //FF sets no defined max length to -1
  1100. if (maxLength < getActiveBufferTemplate().length) getActiveBufferTemplate().length = maxLength;
  1101. if (getActiveMaskSet()['greedy'] == false) {
  1102. getActiveMaskSet()['repeat'] = Math.round(maxLength / getActiveBufferTemplate().length);
  1103. }
  1104. $el.prop('maxLength', getMaskLength() * 2);
  1105. }
  1106. }
  1107. patchValueProperty(el);
  1108. if (opts.numericInput) opts.isNumeric = opts.numericInput;
  1109. if (el.dir == "rtl" || (opts.numericInput && opts.rightAlignNumerics) || (opts.isNumeric && opts.rightAlignNumerics))
  1110. $el.css("text-align", "right");
  1111. if (el.dir == "rtl" || opts.numericInput) {
  1112. el.dir = "ltr";
  1113. $el.removeAttr("dir");
  1114. var inputData = $el.data('_inputmask');
  1115. inputData['isRTL'] = true;
  1116. $el.data('_inputmask', inputData);
  1117. isRTL = true;
  1118. }
  1119. //unbind all events - to make sure that no other mask will interfere when re-masking
  1120. $el.unbind(".inputmask");
  1121. $el.removeClass('focus.inputmask');
  1122. //bind events
  1123. $el.closest('form').bind("submit", function () { //trigger change on submit if any
  1124. if (valueOnFocus != getActiveBuffer().join('')) {
  1125. $el.change();
  1126. }
  1127. }).bind('reset', function () {
  1128. setTimeout(function () {
  1129. $el.trigger("setvalue");
  1130. }, 0);
  1131. });
  1132. $el.bind("mouseenter.inputmask", function () {
  1133. var $input = $(this), input = this;
  1134. if (!$input.hasClass('focus.inputmask') && opts.showMaskOnHover) {
  1135. if (input._valueGet() != getActiveBuffer().join('')) {
  1136. writeBuffer(input, getActiveBuffer());
  1137. }
  1138. }
  1139. }).bind("blur.inputmask", function () {
  1140. var $input = $(this), input = this, nptValue = input._valueGet(), buffer = getActiveBuffer();
  1141. $input.removeClass('focus.inputmask');
  1142. if (valueOnFocus != getActiveBuffer().join('')) {
  1143. $input.change();
  1144. }
  1145. if (opts.clearMaskOnLostFocus && nptValue != '') {
  1146. if (nptValue == getActiveBufferTemplate().join(''))
  1147. input._valueSet('');
  1148. else { //clearout optional tail of the mask
  1149. clearOptionalTail(input);
  1150. }
  1151. }
  1152. if (isComplete(buffer) === false) {
  1153. $input.trigger("incomplete");
  1154. if (opts.clearIncomplete) {
  1155. $.each(masksets, function (ndx, ms) {
  1156. if (typeof (ms) == "object") {
  1157. ms["buffer"] = ms["_buffer"].slice();
  1158. ms["lastValidPosition"] = -1;
  1159. }
  1160. });
  1161. activeMasksetIndex = 0;
  1162. if (opts.clearMaskOnLostFocus)
  1163. input._valueSet('');
  1164. else {
  1165. buffer = getActiveBufferTemplate().slice();
  1166. writeBuffer(input, buffer);
  1167. }
  1168. }
  1169. }
  1170. }).bind("focus.inputmask", function () {
  1171. var $input = $(this), input = this, nptValue = input._valueGet();
  1172. if (opts.showMaskOnFocus && !$input.hasClass('focus.inputmask') && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue == ''))) {
  1173. if (input._valueGet() != getActiveBuffer().join('')) {
  1174. writeBuffer(input, getActiveBuffer(), seekNext(getActiveMaskSet()["lastValidPosition"]));
  1175. }
  1176. }
  1177. $input.addClass('focus.inputmask');
  1178. valueOnFocus = getActiveBuffer().join('');
  1179. }).bind("mouseleave.inputmask", function () {
  1180. var $input = $(this), input = this;
  1181. if (opts.clearMaskOnLostFocus) {
  1182. if (!$input.hasClass('focus.inputmask') && input._valueGet() != $input.attr("placeholder")) {
  1183. if (input._valueGet() == getActiveBufferTemplate().join('') || input._valueGet() == '')
  1184. input._valueSet('');
  1185. else { //clearout optional tail of the mask
  1186. clearOptionalTail(input);
  1187. }
  1188. }
  1189. }
  1190. }).bind("click.inputmask", function () {
  1191. var input = this;
  1192. setTimeout(function () {
  1193. var selectedCaret = caret(input), buffer = getActiveBuffer();
  1194. if (selectedCaret.begin == selectedCaret.end) {
  1195. var clickPosition = isRTL ? TranslatePosition(selectedCaret.begin) : selectedCaret.begin,
  1196. lvp = getActiveMaskSet()["lastValidPosition"],
  1197. lastPosition;
  1198. if (opts.isNumeric) {
  1199. lastPosition = opts.skipRadixDance === false && opts.radixPoint != "" && $.inArray(opts.radixPoint, buffer) != -1 ?
  1200. (opts.numericInput ? seekNext($.inArray(opts.radixPoint, buffer)) : $.inArray(opts.radixPoint, buffer)) :
  1201. seekNext(lvp);
  1202. } else {
  1203. lastPosition = seekNext(lvp);
  1204. }
  1205. if (clickPosition < lastPosition) {
  1206. if (isMask(clickPosition))
  1207. caret(input, clickPosition);
  1208. else caret(input, seekNext(clickPosition));
  1209. } else
  1210. caret(input, lastPosition);
  1211. }
  1212. }, 0);
  1213. }).bind('dblclick.inputmask', function () {
  1214. var input = this;
  1215. setTimeout(function () {
  1216. caret(input, 0, seekNext(getActiveMaskSet()["lastValidPosition"]));
  1217. }, 0);
  1218. }).bind(pasteEvent + ".inputmask dragdrop.inputmask drop.inputmask", function (e) {
  1219. if (skipInputEvent === true) {
  1220. skipInputEvent = false;
  1221. return true;
  1222. }
  1223. var input = this, $input = $(input);
  1224. //paste event for IE8 and lower I guess ;-)
  1225. if (e.type == "propertychange" && input._valueGet().length <= getMaskLength()) {
  1226. return true;
  1227. }
  1228. setTimeout(function () {
  1229. var pasteValue = opts.onBeforePaste != undefined ? opts.onBeforePaste.call(this, input._valueGet()) : input._valueGet();
  1230. checkVal(input, true, false, pasteValue.split(''), true);
  1231. if (isComplete(getActiveBuffer()) === true)
  1232. $input.trigger("complete");
  1233. $input.click();
  1234. }, 0);
  1235. }).bind('setvalue.inputmask', function () {
  1236. var input = this;
  1237. checkVal(input, true);
  1238. valueOnFocus = getActiveBuffer().join('');
  1239. if (input._valueGet() == getActiveBufferTemplate().join(''))
  1240. input._valueSet('');
  1241. }).bind('complete.inputmask', opts.oncomplete
  1242. ).bind('incomplete.inputmask', opts.onincomplete
  1243. ).bind('cleared.inputmask', opts.oncleared
  1244. ).bind("keyup.inputmask", keyupEvent);
  1245. if (androidchrome) {
  1246. $el.bind("input.inputmask", inputEvent);
  1247. } else {
  1248. $el.bind("keydown.inputmask", keydownEvent
  1249. ).bind("keypress.inputmask", keypressEvent);
  1250. }
  1251. if (msie10)
  1252. $el.bind("input.inputmask", inputEvent);
  1253. //apply mask
  1254. checkVal(el, true, false);
  1255. valueOnFocus = getActiveBuffer().join('');
  1256. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  1257. var activeElement;
  1258. try {
  1259. activeElement = document.activeElement;
  1260. } catch (e) {
  1261. }
  1262. if (activeElement === el) { //position the caret when in focus
  1263. $el.addClass('focus.inputmask');
  1264. caret(el, seekNext(getActiveMaskSet()["lastValidPosition"]));
  1265. } else if (opts.clearMaskOnLostFocus) {
  1266. if (getActiveBuffer().join('') == getActiveBufferTemplate().join('')) {
  1267. el._valueSet('');
  1268. } else {
  1269. clearOptionalTail(el);
  1270. }
  1271. } else {
  1272. writeBuffer(el, getActiveBuffer());
  1273. }
  1274. installEventRuler(el);
  1275. }
  1276. }
  1277. //action object
  1278. if (actionObj != undefined) {
  1279. switch (actionObj["action"]) {
  1280. case "isComplete":
  1281. return isComplete(actionObj["buffer"]);
  1282. case "unmaskedvalue":
  1283. isRTL = actionObj["$input"].data('_inputmask')['isRTL'];
  1284. return unmaskedvalue(actionObj["$input"], actionObj["skipDatepickerCheck"]);
  1285. case "mask":
  1286. mask(actionObj["el"]);
  1287. break;
  1288. case "format":
  1289. $el = $({});
  1290. $el.data('_inputmask', {
  1291. 'masksets': masksets,
  1292. 'activeMasksetIndex': activeMasksetIndex,
  1293. 'opts': opts,
  1294. 'isRTL': opts.numericInput
  1295. });
  1296. if (opts.numericInput) {
  1297. opts.isNumeric = opts.numericInput;
  1298. isRTL = true;
  1299. }
  1300. checkVal($el, false, false, actionObj["value"].split(''), true);
  1301. return getActiveBuffer().join('');
  1302. }
  1303. }
  1304. };
  1305. $.inputmask = {
  1306. //options default
  1307. defaults: {
  1308. placeholder: "_",
  1309. optionalmarker: { start: "[", end: "]" },
  1310. quantifiermarker: { start: "{", end: "}" },
  1311. groupmarker: { start: "(", end: ")" },
  1312. escapeChar: "\\",
  1313. mask: null,
  1314. oncomplete: $.noop, //executes when the mask is complete
  1315. onincomplete: $.noop, //executes when the mask is incomplete and focus is lost
  1316. oncleared: $.noop, //executes when the mask is cleared
  1317. repeat: 0, //repetitions of the mask: * ~ forever, otherwise specify an integer
  1318. greedy: true, //true: allocated buffer for the mask and repetitions - false: allocate only if needed
  1319. autoUnmask: false, //automatically unmask when retrieving the value with $.fn.val or value if the browser supports __lookupGetter__ or getOwnPropertyDescriptor
  1320. clearMaskOnLostFocus: true,
  1321. insertMode: true, //insert the input or overwrite the input
  1322. clearIncomplete: false, //clear the incomplete input on blur
  1323. aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js
  1324. onKeyUp: $.noop, //override to implement autocomplete on certain keys for example
  1325. onKeyDown: $.noop, //override to implement autocomplete on certain keys for example
  1326. onBeforePaste: undefined, //executes before masking the pasted value to allow preprocessing of the pasted value. args => pastedValue => return processedValue
  1327. onUnMask: undefined, //executes after unmasking to allow postprocessing of the unmaskedvalue. args => maskedValue, unmaskedValue
  1328. showMaskOnFocus: true, //show the mask-placeholder when the input has focus
  1329. showMaskOnHover: true, //show the mask-placeholder when hovering the empty input
  1330. onKeyValidation: $.noop, //executes on every key-press with the result of isValid. Params: result, opts
  1331. skipOptionalPartCharacter: " ", //a character which can be used to skip an optional part of a mask
  1332. showTooltip: false, //show the activemask as tooltip
  1333. numericInput: false, //numericInput input direction style (input shifts to the left while holding the caret position)
  1334. //numeric basic properties
  1335. isNumeric: false, //enable numeric features
  1336. radixPoint: "", //".", // | ","
  1337. skipRadixDance: false, //disable radixpoint caret positioning
  1338. rightAlignNumerics: true, //align numerics to the right
  1339. //numeric basic properties
  1340. definitions: {
  1341. '9': {
  1342. validator: "[0-9]",
  1343. cardinality: 1
  1344. },
  1345. 'a': {
  1346. validator: "[A-Za-z\u0410-\u044F\u0401\u0451]",
  1347. cardinality: 1
  1348. },
  1349. '*': {
  1350. validator: "[A-Za-z\u0410-\u044F\u0401\u04510-9]",
  1351. cardinality: 1
  1352. }
  1353. },
  1354. keyCode: {
  1355. 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,
  1356. 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
  1357. },
  1358. //specify keycodes which should not be considered in the keypress event, otherwise the preventDefault will stop their default behavior especially in FF
  1359. 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],
  1360. getMaskLength: function (buffer, greedy, repeat, currentBuffer, opts) {
  1361. var calculatedLength = buffer.length;
  1362. if (!greedy) {
  1363. if (repeat == "*") {
  1364. calculatedLength = currentBuffer.length + 1;
  1365. } else if (repeat > 1) {
  1366. calculatedLength += (buffer.length * (repeat - 1));
  1367. }
  1368. }
  1369. return calculatedLength;
  1370. }
  1371. },
  1372. escapeRegex: function (str) {
  1373. var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'];
  1374. return str.replace(new RegExp('(\\' + specials.join('|\\') + ')', 'gim'), '\\$1');
  1375. },
  1376. format: function (value, options) {
  1377. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  1378. resolveAlias(opts.alias, options, opts);
  1379. return maskScope(generateMaskSets(opts), 0, opts, { "action": "format", "value": value });
  1380. }
  1381. };
  1382. $.fn.inputmask = function (fn, options) {
  1383. var opts = $.extend(true, {}, $.inputmask.defaults, options),
  1384. masksets,
  1385. activeMasksetIndex = 0;
  1386. if (typeof fn === "string") {
  1387. switch (fn) {
  1388. case "mask":
  1389. //resolve possible aliases given by options
  1390. resolveAlias(opts.alias, options, opts);
  1391. masksets = generateMaskSets(opts);
  1392. if (masksets.length == 0) { return this; }
  1393. return this.each(function () {
  1394. maskScope($.extend(true, {}, masksets), 0, opts, { "action": "mask", "el": this });
  1395. });
  1396. case "unmaskedvalue":
  1397. var $input = $(this), input = this;
  1398. if ($input.data('_inputmask')) {
  1399. masksets = $input.data('_inputmask')['masksets'];
  1400. activeMasksetIndex = $input.data('_inputmask')['activeMasksetIndex'];
  1401. opts = $input.data('_inputmask')['opts'];
  1402. return maskScope(masksets, activeMasksetIndex, opts, { "action": "unmaskedvalue", "$input": $input });
  1403. } else return $input.val();
  1404. case "remove":
  1405. return this.each(function () {
  1406. var $input = $(this), input = this;
  1407. if ($input.data('_inputmask')) {
  1408. masksets = $input.data('_inputmask')['masksets'];
  1409. activeMasksetIndex = $input.data('_inputmask')['activeMasksetIndex'];
  1410. opts = $input.data('_inputmask')['opts'];
  1411. //writeout the unmaskedvalue
  1412. input._valueSet(maskScope(masksets, activeMasksetIndex, opts, { "action": "unmaskedvalue", "$input": $input, "skipDatepickerCheck": true }));
  1413. //clear data
  1414. $input.removeData('_inputmask');
  1415. //unbind all events
  1416. $input.unbind(".inputmask");
  1417. $input.removeClass('focus.inputmask');
  1418. //restore the value property
  1419. var valueProperty;
  1420. if (Object.getOwnPropertyDescriptor)
  1421. valueProperty = Object.getOwnPropertyDescriptor(input, "value");
  1422. if (valueProperty && valueProperty.get) {
  1423. if (input._valueGet) {
  1424. Object.defineProperty(input, "value", {
  1425. get: input._valueGet,
  1426. set: input._valueSet
  1427. });
  1428. }
  1429. } else if (document.__lookupGetter__ && input.__lookupGetter__("value")) {
  1430. if (input._valueGet) {
  1431. input.__defineGetter__("value", input._valueGet);
  1432. input.__defineSetter__("value", input._valueSet);
  1433. }
  1434. }
  1435. try { //try catch needed for IE7 as it does not supports deleting fns
  1436. delete input._valueGet;
  1437. delete input._valueSet;
  1438. } catch (e) {
  1439. input._valueGet = undefined;
  1440. input._valueSet = undefined;
  1441. }
  1442. }
  1443. });
  1444. break;
  1445. case "getemptymask": //return the default (empty) mask value, usefull for setting the default value in validation
  1446. if (this.data('_inputmask')) {
  1447. masksets = this.data('_inputmask')['masksets'];
  1448. activeMasksetIndex = this.data('_inputmask')['activeMasksetIndex'];
  1449. return masksets[activeMasksetIndex]['_buffer'].join('');
  1450. }
  1451. else return "";
  1452. case "hasMaskedValue": //check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value
  1453. return this.data('_inputmask') ? !this.data('_inputmask')['opts'].autoUnmask : false;
  1454. case "isComplete":
  1455. masksets = this.data('_inputmask')['masksets'];
  1456. activeMasksetIndex = this.data('_inputmask')['activeMasksetIndex'];
  1457. opts = this.data('_inputmask')['opts'];
  1458. return maskScope(masksets, activeMasksetIndex, opts, { "action": "isComplete", "buffer": this[0]._valueGet().split('') });
  1459. case "getmetadata": //return mask metadata if exists
  1460. if (this.data('_inputmask')) {
  1461. masksets = this.data('_inputmask')['masksets'];
  1462. activeMasksetIndex = this.data('_inputmask')['activeMasksetIndex'];
  1463. return masksets[activeMasksetIndex]['metadata'];
  1464. }
  1465. else return undefined;
  1466. default:
  1467. //check if the fn is an alias
  1468. if (!resolveAlias(fn, options, opts)) {
  1469. //maybe fn is a mask so we try
  1470. //set mask
  1471. opts.mask = fn;
  1472. }
  1473. masksets = generateMaskSets(opts);
  1474. if (masksets.length == 0) { return this; }
  1475. return this.each(function () {
  1476. maskScope($.extend(true, {}, masksets), activeMasksetIndex, opts, { "action": "mask", "el": this });
  1477. });
  1478. break;
  1479. }
  1480. } else if (typeof fn == "object") {
  1481. opts = $.extend(true, {}, $.inputmask.defaults, fn);
  1482. resolveAlias(opts.alias, fn, opts); //resolve aliases
  1483. masksets = generateMaskSets(opts);
  1484. if (masksets.length == 0) { return this; }
  1485. return this.each(function () {
  1486. maskScope($.extend(true, {}, masksets), activeMasksetIndex, opts, { "action": "mask", "el": this });
  1487. });
  1488. } else if (fn == undefined) {
  1489. //look for data-inputmask atribute - the attribute should only contain optipns
  1490. return this.each(function () {
  1491. var attrOptions = $(this).attr("data-inputmask");
  1492. if (attrOptions && attrOptions != "") {
  1493. try {
  1494. attrOptions = attrOptions.replace(new RegExp("'", "g"), '"');
  1495. var dataoptions = $.parseJSON("{" + attrOptions + "}");
  1496. $.extend(true, dataoptions, options);
  1497. opts = $.extend(true, {}, $.inputmask.defaults, dataoptions);
  1498. resolveAlias(opts.alias, dataoptions, opts);
  1499. opts.alias = undefined;
  1500. $(this).inputmask(opts);
  1501. } catch (ex) { } //need a more relax parseJSON
  1502. }
  1503. });
  1504. }
  1505. };
  1506. }
  1507. })(jQuery);