<div class="p-3">
<form id="myform">
<div>
<label for="myform_date">Enter Date:</label>
<input type="text" id="myform_date" name="the_date" />
<div class="error hidden" id="date_error">
Please enter a valid date format: MM/DD/YYYY
</div>
</div>
<div class="mt-3">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
.error
{
color: red;
size: 80%
}
.hidden
{
display:none;
}
function validateDate_MMDDYYYY(input_date) {
var parts = input_date.split(/[\/\-\.]/);
if (parts.length < 3) {
return false;
}
var dt = new Date(parts[2], parts[0] - 1, parts[1]);
console.log("date is ", dt.toString());
return (dt && dt.getMonth() === parseInt(parts[0], 10) - 1)
}
function validateForm(event) {
var date_str = document.getElementById('myform_date').value;
if (!validateDate_MMDDYYYY(date_str)) {
document.getElementById('date_error').classList.remove('hidden');
} else {
document.getElementById('date_error').classList.add('hidden');
alert("validation success")
}
event.preventDefault();
}
document.getElementById('myform').addEventListener('submit', validateForm);
This Pen doesn't use any external JavaScript resources.