JSFiddle - React, Tailwind, and code Playground
HTML
<div><input type="text" placeholder="DD/MM/YYYY" data-format="DDMMYYYY" data-pattern="__/__/____" /></div>
<div><input type="text" placeholder="MM/DD/YYYY" data-format="MMDDYYYY" data-pattern="__/__/____" /></div>
<div><input type="text" placeholder="YYYY-MM-DD" data-format="YYYYMMDD" data-pattern="____-__-__" /></div>
<div><input type="text" placeholder="Day: DD, Year: YYYY, Month: MM" data-format="DDYYYYMM" data-pattern="Day: __, Year: ____, Month: __" /></div>
<div id="date-error-msg"></div>
CSS
input {
width: 250px;
}
JavaScript
const patternFreeChar = "_";
const dayValidator = [/^[0-3]$/, /^0[1-9]|[12]\d|3[01]$/];
const monthValidator = [/^[01]$/, /^0[1-9]|1[012]$/];
const yearValidator = [/^[12]$/, /^19|20$/, /^(19|20)\d$/, /^(19|20)\d\d$/];
/**
* Validate a date as your type.
* @param {string} date The date in the provided format as a string representation.
* @param {string} format The format to use.
* @throws {Error} When the date is invalid.
*/
function validateStartTypingDate(date, format='DDMMYYYY') {
if ( !date ) return "";
date = date.substr(0, 8);
if ( !/^\d+$/.test(date) )
throw new Error("Please type numbers only");
const formatAsArray = format.split('');
const dayIndex = formatAsArray.findIndex(c => c == 'D');
const monthIndex = formatAsArray.findIndex(c => c == 'M');
const yearIndex = formatAsArray.findIndex(c => c == 'Y');
const dayStr = date.substr(dayIndex,2);
const monthStr = date.substr(monthIndex,2);
const yearStr = date.substr(yearIndex,4);
if ( dayStr && !dayValidator[dayStr.length-1].test(dayStr) ) {
switch (dayStr.length) {
case 1:
throw new Error("Day in month can start only with 0, 1, 2 or 3");
case 2:
throw new Error("Day in month must be in a range between 01 and 31");
}
}
if ( monthStr && !monthValidator[monthStr.length-1].test(monthStr) ) {
switch (monthStr.length) {
case 1:
throw new Error("Month can start only with 0 or 1");
case 2:
throw new Error("Month number must be in a range between 01 and 12");
}
}
if ( yearStr && !yearValidator[yearStr.length-1].test(yearStr) ) {
switch (yearStr.length) {
case 1:
throw new Error("We support only years between 1900 and 2099, so the full year can start only with 1 or 2");
default:
throw new Error("We support only years between 1900 and 2099, so the full year can start only with 19 or 20");
}
}
const day = parseInt(dayStr);
const month =...