inputmask.date.extensions.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. /*
  2. Input Mask plugin extensions
  3. http://github.com/RobinHerbots/jquery.inputmask
  4. Copyright (c) 2010 - Robin Herbots
  5. Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
  6. Version: 0.0.0-dev
  7. Optional extensions on the jquery.inputmask base
  8. */
  9. (function (factory) {
  10. if (typeof define === "function" && define.amd) {
  11. define(["./inputmask"], factory);
  12. } else if (typeof exports === "object") {
  13. module.exports = factory(require("./inputmask"));
  14. } else {
  15. factory(window.Inputmask);
  16. }
  17. }
  18. (function (Inputmask) {
  19. var $ = Inputmask.dependencyLib;
  20. var //supported codes for formatting
  21. //http://blog.stevenlevithan.com/archives/date-time-format
  22. //https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings?view=netframework-4.7
  23. formatCode = { //regex, valueSetter, type, displayformatter
  24. d: ["[1-9]|[12][0-9]|3[01]", Date.prototype.setDate, "day", Date.prototype.getDate], //Day of the month as digits; no leading zero for single-digit days.
  25. dd: ["0[1-9]|[12][0-9]|3[01]", Date.prototype.setDate, "day", function () {
  26. return pad(Date.prototype.getDate.call(this), 2);
  27. }], //Day of the month as digits; leading zero for single-digit days.
  28. ddd: [""], //Day of the week as a three-letter abbreviation.
  29. dddd: [""], //Day of the week as its full name.
  30. m: ["[1-9]|1[012]", Date.prototype.setMonth, "month", function () {
  31. return Date.prototype.getMonth.call(this) + 1;
  32. }], //Month as digits; no leading zero for single-digit months.
  33. mm: ["0[1-9]|1[012]", Date.prototype.setMonth, "month", function () {
  34. return pad(Date.prototype.getMonth.call(this) + 1, 2);
  35. }], //Month as digits; leading zero for single-digit months.
  36. mmm: [""], //Month as a three-letter abbreviation.
  37. mmmm: [""], //Month as its full name.
  38. yy: ["[0-9]{2}", Date.prototype.setFullYear, "year", function () {
  39. return pad(Date.prototype.getFullYear.call(this), 2);
  40. }], //Year as last two digits; leading zero for years less than 10.
  41. yyyy: ["[0-9]{4}", Date.prototype.setFullYear, "year", function () {
  42. return pad(Date.prototype.getFullYear.call(this), 4);
  43. }],
  44. h: ["[1-9]|1[0-2]", Date.prototype.setHours, "hours", Date.prototype.getHours], //Hours; no leading zero for single-digit hours (12-hour clock).
  45. hh: ["0[1-9]|1[0-2]", Date.prototype.setHours, "hours", function () {
  46. return pad(Date.prototype.getHours.call(this), 2);
  47. }], //Hours; leading zero for single-digit hours (12-hour clock).
  48. hhh: ["[0-9]+", Date.prototype.setHours, "hours", Date.prototype.getHours], //Hours; no limit
  49. H: ["1?[0-9]|2[0-3]", Date.prototype.setHours, "hours", Date.prototype.getHours], //Hours; no leading zero for single-digit hours (24-hour clock).
  50. HH: ["[01][0-9]|2[0-3]", Date.prototype.setHours, "hours", function () {
  51. return pad(Date.prototype.getHours.call(this), 2);
  52. }], //Hours; leading zero for single-digit hours (24-hour clock).
  53. HHH: ["[0-9]+", Date.prototype.setHours, "hours", Date.prototype.getHours], //Hours; no limit
  54. M: ["[1-5]?[0-9]", Date.prototype.setMinutes, "minutes", Date.prototype.getMinutes], //Minutes; no leading zero for single-digit minutes. Uppercase M unlike CF timeFormat's m to avoid conflict with months.
  55. MM: ["[0-5][0-9]", Date.prototype.setMinutes, "minutes", function () {
  56. return pad(Date.prototype.getMinutes.call(this), 2);
  57. }], //Minutes; leading zero for single-digit minutes. Uppercase MM unlike CF timeFormat's mm to avoid conflict with months.
  58. s: ["[1-5]?[0-9]", Date.prototype.setSeconds, "seconds", Date.prototype.getSeconds], //Seconds; no leading zero for single-digit seconds.
  59. ss: ["[0-5][0-9]", Date.prototype.setSeconds, "seconds", function () {
  60. return pad(Date.prototype.getSeconds.call(this), 2);
  61. }], //Seconds; leading zero for single-digit seconds.
  62. l: ["[0-9]{3}", Date.prototype.setMilliseconds, "milliseconds", function () {
  63. return pad(Date.prototype.getMilliseconds.call(this), 3);
  64. }], //Milliseconds. 3 digits.
  65. L: ["[0-9]{2}", Date.prototype.setMilliseconds, "milliseconds", function () {
  66. return pad(Date.prototype.getMilliseconds.call(this), 2);
  67. }], //Milliseconds. 2 digits.
  68. t: ["[ap]"], //Lowercase, single-character time marker string: a or p.
  69. tt: ["[ap]m"], //two-character time marker string: am or pm.
  70. T: ["[AP]"], //single-character time marker string: A or P.
  71. TT: ["[AP]M"], //two-character time marker string: AM or PM.
  72. Z: [""], //US timezone abbreviation, e.g. EST or MDT. With non-US timezones or in the Opera browser, the GMT/UTC offset is returned, e.g. GMT-0500
  73. o: [""], //GMT/UTC timezone offset, e.g. -0500 or +0230.
  74. S: [""] //The date's ordinal suffix (st, nd, rd, or th).
  75. },
  76. formatAlias = {
  77. isoDate: "yyyy-mm-dd", //2007-06-09
  78. isoTime: "HH:MM:ss", //17:46:21
  79. isoDateTime: "yyyy-mm-dd'T'HH:MM:ss", //2007-06-09T17:46:21
  80. isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'" //2007-06-09T22:46:21Z
  81. };
  82. function getTokenizer(opts) {
  83. if (!opts.tokenizer) {
  84. var tokens = [];
  85. for (var ndx in formatCode) {
  86. if (tokens.indexOf(ndx[0]) === -1)
  87. tokens.push(ndx[0]);
  88. }
  89. opts.tokenizer = "(" + tokens.join("+|") + ")+?|.";
  90. opts.tokenizer = new RegExp(opts.tokenizer, "g");
  91. }
  92. return opts.tokenizer;
  93. }
  94. function isValidDate(dateParts, currentResult) {
  95. return !isFinite(dateParts.rawday)
  96. || (dateParts.day == "29" && !isFinite(dateParts.rawyear))
  97. || new Date(dateParts.date.getFullYear(), isFinite(dateParts.rawmonth) ? dateParts.month : dateParts.date.getMonth() + 1, 0).getDate() >= dateParts.day
  98. ? currentResult
  99. : false; //take corrective action if possible
  100. }
  101. function isDateInRange(dateParts, opts) {
  102. var result = true;
  103. if (opts.min) {
  104. if (dateParts["rawyear"]) {
  105. var rawYear = dateParts["rawyear"].replace(/[^0-9]/g, ""),
  106. minYear = opts.min.year.substr(0, rawYear.length);
  107. result = minYear <= rawYear;
  108. }
  109. if (dateParts["year"] === dateParts["rawyear"]) {
  110. if (opts.min.date.getTime() === opts.min.date.getTime()) {
  111. result = opts.min.date.getTime() <= dateParts.date.getTime();
  112. }
  113. }
  114. }
  115. if (result && opts.max && opts.max.date.getTime() === opts.max.date.getTime()) {
  116. result = opts.max.date.getTime() >= dateParts.date.getTime();
  117. }
  118. return result;
  119. }
  120. //parse the given format and return a mask pattern
  121. //when a dateObjValue is passed a datestring in the requested format is returned
  122. function parse(format, dateObjValue, opts, raw) {
  123. //parse format to regex string
  124. var mask = "", match;
  125. while (match = getTokenizer(opts).exec(format)) {
  126. if (dateObjValue === undefined) {
  127. if (formatCode[match[0]]) {
  128. mask += "(" + formatCode[match[0]][0] + ")";
  129. } else {
  130. switch (match[0]) {
  131. case "[":
  132. mask += "(";
  133. break;
  134. case "]":
  135. mask += ")?";
  136. break;
  137. default:
  138. mask += Inputmask.escapeRegex(match[0]);
  139. }
  140. }
  141. }
  142. else {
  143. if (formatCode[match[0]]) {
  144. if (raw !== true && formatCode[match[0]][3]) {
  145. var getFn = formatCode[match[0]][3];
  146. mask += getFn.call(dateObjValue.date);
  147. }
  148. else if (formatCode[match[0]][2]) mask += dateObjValue["raw" + formatCode[match[0]][2]];
  149. else mask += match[0];
  150. }
  151. else mask += match[0];
  152. }
  153. }
  154. return mask;
  155. }
  156. //padding function
  157. function pad(val, len) {
  158. val = String(val);
  159. len = len || 2;
  160. while (val.length < len) val = "0" + val;
  161. return val;
  162. }
  163. function analyseMask(maskString, format, opts) {
  164. var dateObj = {"date": new Date(1, 0, 1)}, targetProp, mask = maskString, match, dateOperation, targetValidator;
  165. function extendProperty(value) {
  166. var correctedValue = value.replace(/[^0-9]/g, "0");
  167. if (correctedValue != value) { //only do correction on incomplete values
  168. //determine best validation match
  169. var enteredPart = value.replace(/[^0-9]/g, ""),
  170. min = (opts.min && opts.min[targetProp] || value).toString(),
  171. max = (opts.max && opts.max[targetProp] || value).toString();
  172. correctedValue = enteredPart + (enteredPart < min.slice(0, enteredPart.length) ? min.slice(enteredPart.length) : (enteredPart > max.slice(0, enteredPart.length) ? max.slice(enteredPart.length) : correctedValue.toString().slice(enteredPart.length)));
  173. }
  174. return correctedValue;
  175. }
  176. function setValue(dateObj, value, opts) {
  177. dateObj[targetProp] = extendProperty(value);
  178. dateObj["raw" + targetProp] = value;
  179. if (dateOperation !== undefined)
  180. dateOperation.call(dateObj.date, targetProp == "month" ? parseInt(dateObj[targetProp]) - 1 : dateObj[targetProp]);
  181. }
  182. if (typeof mask === "string") {
  183. while (match = getTokenizer(opts).exec(format)) {
  184. var value = mask.slice(0, match[0].length);
  185. if (formatCode.hasOwnProperty(match[0])) {
  186. targetValidator = formatCode[match[0]][0];
  187. targetProp = formatCode[match[0]][2];
  188. dateOperation = formatCode[match[0]][1];
  189. setValue(dateObj, value, opts);
  190. }
  191. mask = mask.slice(value.length);
  192. }
  193. return dateObj;
  194. } else if (mask && typeof mask === "object" && mask.hasOwnProperty("date")) {
  195. return mask;
  196. }
  197. return undefined;
  198. }
  199. Inputmask.extendAliases({
  200. "datetime": {
  201. mask: function (opts) {
  202. //localize
  203. formatCode.S = opts.i18n.ordinalSuffix.join("|");
  204. opts.inputFormat = formatAlias[opts.inputFormat] || opts.inputFormat; //resolve possible formatAkias
  205. opts.displayFormat = formatAlias[opts.displayFormat] || opts.displayFormat || opts.inputFormat; //resolve possible formatAkias
  206. opts.outputFormat = formatAlias[opts.outputFormat] || opts.outputFormat || opts.inputFormat; //resolve possible formatAkias
  207. opts.placeholder = opts.placeholder !== "" ? opts.placeholder : opts.inputFormat.replace(/[\[\]]/, "");
  208. opts.regex = parse(opts.inputFormat, undefined, opts);
  209. // console.log(opts.regex);
  210. return null; //migrate to regex mask
  211. },
  212. placeholder: "", //set default as none (~ auto); when a custom placeholder is passed it will be used
  213. inputFormat: "isoDateTime", //format used to input the date
  214. displayFormat: undefined, //visual format when the input looses focus
  215. outputFormat: undefined, //unmasking format
  216. min: null, //needs to be in the same format as the inputfornat
  217. max: null, //needs to be in the same format as the inputfornat,
  218. // Internationalization strings
  219. i18n: {
  220. dayNames: [
  221. "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun",
  222. "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
  223. ],
  224. monthNames: [
  225. "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
  226. "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
  227. ],
  228. ordinalSuffix: ["st", "nd", "rd", "th"]
  229. },
  230. postValidation: function (buffer, pos, currentResult, opts) {
  231. opts.min = analyseMask(opts.min, opts.inputFormat, opts);
  232. opts.max = analyseMask(opts.max, opts.inputFormat, opts);
  233. var result = currentResult, dateParts = analyseMask(buffer.join(""), opts.inputFormat, opts);
  234. if (result && dateParts.date.getTime() === dateParts.date.getTime()) { //check for a valid date ~ an invalid date returns NaN which isn't equal
  235. result = isValidDate(dateParts, result);
  236. result = result && isDateInRange(dateParts, opts);
  237. }
  238. if (pos && result && currentResult.pos !== pos) {
  239. return {
  240. buffer: parse(opts.inputFormat, dateParts, opts),
  241. refreshFromBuffer: {start: pos, end: currentResult.pos}
  242. };
  243. }
  244. return result;
  245. },
  246. onKeyDown: function (e, buffer, caretPos, opts) {
  247. var input = this;
  248. if (e.ctrlKey && e.keyCode === Inputmask.keyCode.RIGHT) {
  249. var today = new Date(), match, date = "";
  250. while (match = getTokenizer(opts).exec(opts.inputFormat)) {
  251. if (match[0].charAt(0) === "d") {
  252. date += pad(today.getDate(), match[0].length);
  253. } else if (match[0].charAt(0) === "m") {
  254. date += pad((today.getMonth() + 1), match[0].length);
  255. } else if (match[0] === "yyyy") {
  256. date += today.getFullYear().toString();
  257. } else if (match[0].charAt(0) === "y") {
  258. date += pad(today.getYear(), match[0].length);
  259. }
  260. }
  261. input.inputmask._valueSet(date);
  262. $(input).trigger("setvalue");
  263. }
  264. },
  265. onUnMask: function (maskedValue, unmaskedValue, opts) {
  266. return parse(opts.outputFormat, analyseMask(maskedValue, opts.inputFormat, opts), opts, true);
  267. },
  268. casing: function (elem, test, pos, validPositions) {
  269. if (test.nativeDef.indexOf("[ap]") == 0) return elem.toLowerCase();
  270. if (test.nativeDef.indexOf("[AP]") == 0) return elem.toUpperCase();
  271. return elem;
  272. },
  273. insertMode: false
  274. }
  275. });
  276. return Inputmask;
  277. }
  278. ))
  279. ;