Why does my custom validator not work?

I have a form with a birthdate field and a custom validator that SHOULD validate if the person filling out the form is at least 16 years old.  As I have it now, I can't seem to get the error message to show up regardless of what I put in the field.  
public void validateDOB(object sender, ServerValidateEventArgs e)
        {
 
            // Declare variables.
            DateTime dtDOB = new DateTime();
            DateTime dtTest = new DateTime();
            DateTime dtDOBMinus16Years = new DateTime();
 
            // Get the registrant's birthdate.
            String strDateFormat = "MM/dd/yyyy";
            dtDOB = DateTime.ParseExact(Server.HtmlEncode(txtBirthDate.Text), strDateFormat, CultureInfo.InvariantCulture);
 
            // Get the date 16 years ago.
            dtTest = DateTime.Today.AddYears(-16);
 
            // Get DOB minus 16 years.
            dtDOBMinus16Years = dtDOB.AddYears(-16);
 
            // Compare them.
            if (dtDOBMinus16Years < dtTest)
            {
                e.IsValid = false;
            }
            else
            {
                e.IsValid = true;
            }
 
        }
 
// ASPX:
 
<asp:CustomValidator ID="vldBirthDateAge" runat="server" OnServerValidate="validateDOB" ErrorMessage="You must be 16 or older to register for these classes." Display="None" />
 
Jeremy

Open in new window

mrcoulsonAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

guru_samiCommented:
I don't see any ControlToValidate property set...
Also make sure to set the ValidationGroup property if you are using it for other controls.
0
mrcoulsonAuthor Commented:
Hey, yeah, I had taken the ControlToValidate property off to see if that would make a difference.  I added it back and it was still not working.

This validator only validates one control, so there's no group necessary, right?

Jeremy
0
guru_samiCommented:
Hold on ...i see you have Display="None"?
Change it to Static or Dynamic...
ValidationGroup is not necessary ...but make sure either it is set for all or none controls participating in Validation.
0
JavaScript Best Practices

Save hours in development time and avoid common mistakes by learning the best practices to use for JavaScript.

mrcoulsonAuthor Commented:
ValidationGroup isn't anywhere around.

I changed the Display but that made no difference.

I'm attaching the part of my ASPX with all of the validators and the control I'm validating.
<%-- Control: --%>
<asp:TextBox ID="txtBirthDate" runat="server" />
 
<%-- All of my validators and my summary: --%>
<asp:ValidationSummary ID="vldSummary" runat="server" />
<asp:CustomValidator ID="vldFirstName" runat="server" EnableClientScript="true" ClientValidationFunction="validateFirstName" ErrorMessage="Please enter your first name." Display="None" />
<asp:CustomValidator ID="vldLastName" runat="server" EnableClientScript="true" ClientValidationFunction="validateLastName" ErrorMessage="Please enter your last name." Display="None" />
<asp:RequiredFieldValidator ID="vldBirthDate" runat="server" ControlToValidate="txtBirthDate" ErrorMessage="Please enter your birthdate." Display="None" />
<asp:RegularExpressionValidator ID="vldBirthDateFormat" runat="server" ControlToValidate="txtBirthDate" ErrorMessage="Please enter a valid birthdate." ValidationExpression="^([1-9]|1[0-2])/([1-9]|[12][0-9]|3[01])/\d{4}$" Display="None" />
<asp:CustomValidator ID="vldBirthDateAge" runat="server" ControlToValidate="txtBirthDate" OnServerValidate="validateDOB" ValidateEmptyText="true" ErrorMessage="You must be 16 or older to register for these classes." Display="None" />
<asp:RequiredFieldValidator ID="vldSSN" runat="server" ControlToValidate="txtSSN" ErrorMessage="Please enter the last 4 digits of your social security number." Display="None" />
<asp:RequiredFieldValidator ID="vldMailingAddress" runat="server" ControlToValidate="txtMailingAddress" ErrorMessage="Please enter your mailing address." Display="None" />
<asp:RequiredFieldValidator ID="vldMailingCity" runat="server" ControlToValidate="txtMailingCity" ErrorMessage="Please enter your mailing address city." Display="None" />
<asp:RequiredFieldValidator ID="vldMailingState" runat="server" ControlToValidate="ddlMailingState" ErrorMessage="Please enter your mailing address state" Display="None" />
<asp:RequiredFieldValidator ID="vldMailingZip" runat="server" ControlToValidate="txtMailingZip" ErrorMessage="Please enter your mailing address zip code." Display="None" />
<asp:CustomValidator ID="vldPhone" runat="server" EnableClientScript="true" ClientValidationFunction="validatePhone" ErrorMessage="Please enter at least one phone number." Display="None" />
<asp:CustomValidator ID="vldAcceptTerms" runat="server" EnableClientScript="true" ClientValidationFunction="validateTerms" ErrorMessage="Please accept the terms & conditions." Display="None" />

Open in new window

0
guru_samiCommented:
One more question...did you set breakpoint in your validateDOB method and see if atleast you method is being called or not?
0
mrcoulsonAuthor Commented:
Unfortunately, I can't use that.  Unless there's a way to change it that I don't know about (quite possible), the testing server in VS uses localhost.  On our network, any request for localhost goes directly to the proxy's home page.  Yes, it's annoying.

Jeremy
0
guru_samiCommented:
Looks its your code...try this:

// Declare variables.
        DateTime dtDOB = new DateTime();
        DateTime dtTest = new DateTime();
        DateTime dtDOBPlus16Years = new DateTime();

        // Get the registrant's birthdate.
        String strDateFormat = "MM/dd/yyyy";
        dtDOB = DateTime.ParseExact(Server.HtmlEncode(TextBox1.Text), strDateFormat, CultureInfo.InvariantCulture);

        // Get the date 16 years ago.
        dtTest = DateTime.Today.Date;
       

        // Get DOB minus 16 years.
        dtDOBPlus16Years = dtDOB.AddYears(16).Date;

        // Compare them.
        if (dtDOBPlus16Years > dtTest)
        {
            e.IsValid = false;
        }
        else
        {
            e.IsValid = true;
        }
0
mrcoulsonAuthor Commented:
No change, my friend.

Jeremy
0
guru_samiCommented:
This is the code working for me:
<asp:TextBox ID="txtBirthDate" runat="server" />
        <asp:CustomValidator ID="vldBirthDateAge" runat="server"
        ControlToValidate="txtBirthDate"
        OnServerValidate="validateDOB" ValidateEmptyText="true"
        ErrorMessage="You must be 16 or older to register for these classes."
        Display="None" />
       <asp:ValidationSummary ID="vldSummary" runat="server" />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />

----------------
protected void validateDOB(object source, ServerValidateEventArgs e)
    {
        // Declare variables.
        DateTime dtDOB = new DateTime();
        DateTime dtTest = new DateTime();
        DateTime dtDOBPlus16Years = new DateTime();

        // Get the registrant's birthdate.
        String strDateFormat = "MM/dd/yyyy";
        if (!string.IsNullOrEmpty(txtBirthDate.Text))
        {
            dtDOB = DateTime.ParseExact(Server.HtmlEncode(txtBirthDate.Text), strDateFormat, CultureInfo.InvariantCulture);

            // Get the date 16 years ago.
            dtTest = DateTime.Today.Date;

            // Get DOB minus 16 years.
            dtDOBPlus16Years = dtDOB.AddYears(16).Date;

            // Compare them.
            if (dtDOBPlus16Years > dtTest)
            {
                e.IsValid = false;
            }
            else
            {
                e.IsValid = true;
            }
        }
        else
        {
            e.IsValid = false;
        }
    }
0
mrcoulsonAuthor Commented:
Well, why is it failing here?  I'm so close to telling this guy that he'll have to accept applications from people who are too young.

Is there altogether some other way to do this?

Jeremy
0
guru_samiCommented:
for troubleshooting purpose...can you just put this line inside of your function like:

protected void validateDOB(object source, ServerValidateEventArgs e)
    {
           Respose.Write(txtBirthDate.Text)
//all other code as before
}
observe the output for these two inputs:
1: 5/15/1995
2: 11/10/1995
0
mrcoulsonAuthor Commented:
Okay!  I got it working.  It after all my script.

So, here's my question for you since I may still have your attention:

If I enter a birthdate of less than 16 years of age and I leave another field blank, the blank fields show up in the summary, but not the custom validator about the age.  That only works if every RequiredFieldValidator is made happy.  Any reason for that?

Jeremy
0
guru_samiCommented:
The reason for that is the CustomValidator uses OnServerValidate event i.e. validation is done at server side while for other Validators Validation is done on ClientSide....
Solutions:
1: Do client-side validation for CustomValidator using Use ClientValidationFunction. Here you need to do same what you are doing onServerValidate ..but the syntax might change due to JavaScript
Or
2: Disable ClientSide Validation for rest of the controls. This can be done by setting EnableClientScript=False for all other Validator Controls. The down-side is you have to let go the benefits of using client script.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
mrcoulsonAuthor Commented:
Okay.  I will try option 1.  I have some client-side validation scripts, so 2 seems like some trouble.

Jeremy
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.