I am defiately a noob in regex, i had the code which is working good but the problem is that validation of date is not perfect, it checks for 2 disits of date and 2 digits of month and 2 digits of year but i want to have a proper validation of date using a regex, even my code works but it is missing the validation of date,
Many will suggest to use date field, but as per requirement, i cannot do so.
Here is the fiddle i have
https://jsfiddle.net/05oe4hzn/
Fiddle code is here
<form action="">
<input class="startDate date" data-message="Invalid start date"
placeholder="DD/MM/YYYY" />
<input class="endDate date" data-message="Invalid end date"
placeholder="DD/MM/YYYY" />
<input type="submit">
</form>
<hr/>
<form action="">
<input class="startDate date" data-message="Invalid start date"
placeholder="MM/DD/YYYY" />
<input class="endDate date" data-message="Invalid end date"
placeholder="MM/DD/YYYY" />
<input type="submit">
</form>
and a JS Code
const dateRegex = {
"MM/DD/YYYY": /(?<month>d{2})/(?<day>d{2})/(?<year>d{4})/,
"DD/MM/YYYY": /(?<day>d{2})/(?<month>d{2})/(?<year>d{4})/
};
const getDate = (dateString, format) => {
const result = dateRegex[format].exec(dateString);
if (!result) return -1;
const { year,month,day } = result.groups; // spread
const date = new Date(year, month-1, day, 15, 0, 0, 0);
console.log(dateString,year,month,day,"n",date)
return isNaN(date) ? -1 : [date, +year, +month, +day]; // return date and parts
};
const validateDate = formElement => {
const value = formElement.value.trim();
if (value === "") return true; // only test actual values
const dateValid = getDate(value, formElement.placeholder)
if (dateValid === -1) return false; // not matching format
const [date, year, month, day] = dateValid;
console.log(date.getFullYear(),"===",year,date.getMonth(),"===",(month - 1),date.getDate(),"===",day); // remove this after testing
return date.getFullYear() === year &&
date.getMonth() === (month - 1) &&
date.getDate() === day;
};
$("form").on("submit", function(e) { // passing the submit event
$(".date",this).each(function() { // only the dates in this form
if (!validateDate(this)) {
alert($(this).data("message"));
$(this).focus();
e.preventDefault();
return false; // stop processing dates
}
})
})