Solved

Why does my custom validator not work?

Posted on 2009-07-14
14
444 Views
Last Modified: 2012-05-07
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

0
Comment
Question by:mrcoulson
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 7
14 Comments
 
LVL 41

Expert Comment

by:guru_sami
ID: 24852111
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
 

Author Comment

by:mrcoulson
ID: 24852175
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
 
LVL 41

Expert Comment

by:guru_sami
ID: 24852311
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:mrcoulson
ID: 24852358
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
 
LVL 41

Expert Comment

by:guru_sami
ID: 24852392
One more question...did you set breakpoint in your validateDOB method and see if atleast you method is being called or not?
0
 

Author Comment

by:mrcoulson
ID: 24852437
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
 
LVL 41

Expert Comment

by:guru_sami
ID: 24852464
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
 

Author Comment

by:mrcoulson
ID: 24852518
No change, my friend.

Jeremy
0
 
LVL 41

Expert Comment

by:guru_sami
ID: 24852608
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
 

Author Comment

by:mrcoulson
ID: 24852659
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
 
LVL 41

Expert Comment

by:guru_sami
ID: 24852821
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
 

Author Comment

by:mrcoulson
ID: 24858794
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
 
LVL 41

Accepted Solution

by:
guru_sami earned 500 total points
ID: 24860000
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
 

Author Comment

by:mrcoulson
ID: 24861164
Okay.  I will try option 1.  I have some client-side validation scripts, so 2 seems like some trouble.

Jeremy
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This video Micro Tutorial shows how to password-protect PDF files with free software. Many software products can do this, such as Adobe Acrobat (but not Adobe Reader), Nuance PaperPort, and Nuance Power PDF, but they are not free products. This vide…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…

691 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question