Solved

Why does my custom validator not work?

Posted on 2009-07-14
14
428 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
  • 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
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 

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

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

776 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