I have been trying for days to create a function that validates if the input type=Date is not empty and that the Date is formatted correctly. I want the following logic and actions:
- If the field is empty, display an error message: "* is required"
- If the field is formatted incorrectly meaning it does not meet this criterion: yyyy-mm-dd and 'mm' does not exceed 12 and 'dd' does not exceed 31 then display an error message "* invalid date"
Here is my code thus far:
HTML
<!-- Date of Birth -->
<label for="dateOfBirth">Date of Birth</label>
<span id="dateOfBirthErr" class="Error">*</span>
<br>
<input type="text" id="dateOfBirth" name="dateOfBirth" onfocus="(this.type='date')"
onblur="dateOfBirthValdiate()" placeholder="<?php echo date('Y-m-d'); ?>" max="9999-12-31" min="1800-01-01" />
JS
// Date of Birth Validation
function dateOfBirthValdiate () {
let dateOfBirth = document.forms["registrationForm"]["dateOfBirth"];
let dateOfBirthErr = document.getElementById("dateOfBirthErr");
const dateFormat = /^\d{4}[\-\/\s]?((((0[13578])|(1[02]))[\-\/\s]?(([0-2][0-9])|(3[01])))|(((0[469])|(11))[\-\/\s]?(([0-2][0-9])|(30)))|(02[\-\/\s]?[0-2][0-9]))$/;
if (dateOfBirth.value == "") {
dateOfBirth.style.border = "2px solid red";
dateOfBirthErr.innerHTML = "* is required";
} else if (dateOfBirth.value.match(dateFormat)) {
dateOfBirth.style.border = "1px solid #ccc";
dateOfBirthErr.innerHTML = "*";
} else {
dateOfBirth.style.border = "2px solid red";
dateOfBirthErr.innerHTML = "invalid date"
}
}
I am new to RegEx so the issue be with my this code, however, when I test it in other code snippets it seems to work fine. I appreciate any help!