I am encountering issues with the CustomValidation control as I am trying to validate if the year entered in the date of birth field is at least 20 years less than the graduation year selected from a drop-down list. I attempted to use the ClientValidationFunction as follows:
<asp:CustomValidator ID="BirthYearCustomValidator" runat="server" ControlToValidate="ddlGraduationYear" ErrorMessage="Enter a valid graduation year." SetFocusOnError="true" ValidationGroup="SaveEducationStep" Display="Dynamic" ClientValidationFunction="GraduationYearValidation"></asp:CustomValidator>
Here is the script provided:
<script type="text/javascript">
function GraduationYearValidation(sender, args) {
var brithYear = parseInt(new Date(document.getElementById('<%=txtBirthDate.ClientID%>').value).getFullYear());
var gradeYear = parseInt(document.getElementById('<%=ddlGraduationYear.ClientID%>').options[document.getElementById('<%=ddlGraduationYear.ClientID%>').selectedIndex].text);
if ((brithYear - gradeYear) < 20) {
return args.IsValid = true;
}
else {
return args.IsValid = false;
}
}
I encountered errors stating "document.getElementById(...) is null" and "GraduationYearValidation is not defined."
Therefore, I attempted to perform server-side validation by:
<asp:CustomValidator ID="BirthYearCustomValidator" runat="server" ControlToValidate="ddlGraduationYear" ErrorMessage="enter a valid graduation year." SetFocusOnError="true" ValidationGroup="SaveEducationStep" Display="Dynamic" OnServerValidate="BirthYearCustomValidator_ServerValidate"></asp:CustomValidator>
The code behind includes:
protected void BirthYearCustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
int brithYear = Convert.ToDateTime(txtBirthDate.Text).Year;
int gradeYear = Convert.ToInt32(ddlGraduationYear.SelectedValue);
if ((gradeYear - brithYear) < 20)
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
Despite implementing
Page.Validate("SaveEducationStep");
and checking Page.IsValid
before saving, the solution did not work for me. Any suggestions regarding both scenarios would be greatly appreciated. Thank you.