I have problems in using CustomValidation control, I want to check if year entered in date of birth text field is less than graduation year selected from a drop down list by 20 years. I think using ClientValidationFunction is much better when i tried to use it:

<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 get those errors: document.getElementById(...) is null and GraduationYearValidation is not defined.

so, i tried to make it server side 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>

code behind is :

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;
            args.IsValid = true;

it doen't work and i searched for the reason i found it may be because i need to write Page.Validate("SaveEducationStep"); and check if Page.IsValid before save, but it still not working with me any suggestion on both scenarios will be appreciated. thanks.

Member Avatar

Custom ASPNET validators are difficult to build and debug.

I would try setting the ClientIDMode of the elements to Static and update the script to reference the actual IDs to see if that helps resolves the reference error.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.