I have 3 separate input fields for DOB. My validation would check for:
- input pattern, the format should only accept dd/mm/yyyy
- input values are within certain bounds
- leap years
I have tried combining a solution I found online with my own code. When I try to validate the date the error message is displayed even if the data is correct. Does anyone have a solution for this?
http://jsfiddle.net/noemitotos/5t9wboaq/10/
$(".btn").on ('click', function() {
// Combine date
var day = $('#dob_day').val();
var month = $('#dob_month').val();
var year = $('#dob_year').val();
var dateString = day + "/" + month + "/" + year;
console.log(dateString);
// First check for the pattern
if (!/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/.test(dateString)) {
console.log('false pattern');
return false;
}
// Check the ranges of month and year
if (year < 1911 || year > 2011 || month == 0 || month > 12) {
console.log('incorrect month/year ranges');
return false;
}
var monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// Adjust for leap years
if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
monthLength[1] = 29;
// Check the range of the day
return day > 0 && day <= monthLength[month - 1];
});
And my markup:
<input type="text" value="" placeholder="DD" name="customer[dob]" id="dob_day" class="large" /> /
<input type="text" value="" placeholder="MM" name="customer[dob]" id="dob_month" class="large" /> /
<input type="text" value="" placeholder="YYYY" name="customer[dob]" id="dob_year" class="large" />
<button class="btn" type="submit" value="">Validate</button>