I have a set of combo boxes on a HTML form which act as a Date control:
<div id="datecheck">
<select id="datecheck_y" name="datecheck_y">
<option value="2009">2009</option>
<option value="2008">2008</option>
<option value=""></option>
</select>
<select id="datecheck_m" name="datecheck_m" >
<option value="1">Jab</option>
<option value="2">Feb</option>
<option value=""></option>
</select>
<select id="datecheck_d" name="datecheck_d" >
<option value="1">1</option>
<option value="31">31</option>
<option value=""></option>
</select>
</div>
No I want to validate whether the user has left any value (year/month/day) as blank, or if the values form a valid date (example invalid date: 2009(datecheck_y),Feb(datecheck_m),31(datecheck_d)
For this I wrote two custom rules in JQuery, here is my approach:
I have two custom rules (REQUIRED_DATE, VALID_DATE):
$().ready(function() {
$.validator.addMethod("REQUIRED_DATE", function(value, element) {
CheckBlankDate(element);
}, "Date cannot be left blank");
$.validator.addMethod("VALID_DATE", function(value, element) {
return this.optional(element) || CheckDate(element);
}, "Date should be valid");
$("#form1").validate({
rules: {
datecheck: { REQUIRED_DATE: true,VALID_DATE: true }
},
messages: {
datecheck:
{
REQUIRED_DATE: "Date is required",
VALID_DATE: "Date should be valid"
}
}
});
});
Here are the CheckDate, CheckDateBlank JavaScript functions for reference:
function ValidateDate(y, mo, d, h, mi, s) {
var date = new Date(y, mo - 1, d, h, mi, s, 0);
var ny = date.getFullYear();
var nmo = date.getMonth() + 1;
var nd = date.getDate();
var nh = date.getHours();
var nmi = date.getMinutes();
var ns = date.getSeconds();
var flag = (ny == y && nmo == mo && nd == d && nh == h && nmi == mi && ns == s);
return (flag);
}
function CheckDate(dateElement) {
var y, mo, d, h, mi, s;
y = document.getElementById(dateElement.id + '_y').value;
mo = document.getElementById(dateElement.id + '_m').value;
d = document.getElementById(dateElement.id + '_d').value;
h = document.getElementById(dateElement.id + '_h').value;
mi = document.getElementById(dateElement.id + '_min').value;
s = 0;
return ValidateDate(y, mo, d, h, mi, s);
}
function CheckBlankDate(dateElement) {
var y, mo, d, h, mi, s;
y = document.getElementById(dateElement.id + '_y').value;
mo = document.getElementById(dateElement.id + '_m').value;
d = document.getElementById(dateElement.id + '_d').value;
h = document.getElementById(dateElement.id + '_h').value;
mi = document.getElementById(dateElement.id + '_min').value;
s = 0;
if(y=="" || mo =="" || d=="")
{
return false;
}
return true;
}
This approach does not work, as I believe JQuery cannot find any input element with name "datecheck". Is there any other approach that we can follow?