Solved

Programming Validation Controls

Posted on 2008-06-19
9
169 Views
Last Modified: 2010-04-15
I am trying to program validation controls on my web page.  How would I program it so it only validates when the drop down list box is the United States?  See below:

<asp:RegularExpressionValidator ID="RegularExpressionValidator3" runat="server"
                    ControlToValidate="newZipcode" ErrorMessage="*Incorrect Zip Code"
                    ValidationExpression="\d{5}(-\d{4})?" ValidationGroup="NewUserGroup"></asp:RegularExpressionValidator>
0
Comment
Question by:VBBRett
  • 5
  • 4
9 Comments
 
LVL 16

Expert Comment

by:ororiole
Comment Utility
Use a custom validator and implement its event handler to do the test. Set RegularExpressionValidator3 Enabled=false in page_Load.

CustomValidator_ServerValidate( blah, blah)
{
if (ddl1.Selelcted.Value == "United States")
{
  RegularExpressionValidator3.Enabled = true;
  RegularExpressionValidator3.Validate();
}
}

Or you could just eliminate RegularExpressionValidator3 and do the regex test yourself in your custom validator. That would be cleaner.


 
0
 

Author Comment

by:VBBRett
Comment Utility
Would this work?  countries is the drop down list box.  RegularExpressionValidator is the validation control for zip codes.  Basically if the user is from out of the country, I don't want the US zip code validation control to activate.  So, is what I am doing correct?See below:

 protected void countries_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (countries!= "United States")
        {
            this.RegularExpressionValidator3.Enabled = false;
        }
    }
0
 

Author Comment

by:VBBRett
Comment Utility
With the code that I posted, i get the error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'string'
0
 

Author Comment

by:VBBRett
Comment Utility
Can you please expand on custom validators please?  Thanks!
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 16

Expert Comment

by:ororiole
Comment Utility
you could use the selected index changed event, its a good idea, if you dont mind it posting back. This will fix your error:
protected void countries_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (countries.SelectedValue != "United States")
        {
            this.RegularExpressionValidator3.Enabled = false;
        }
        else
           this.RegularExpressionValidator3.Enabled = true;
    }
and that takes care of the problem. However, if you wish to use a custom validator here is an example.


        <asp:CustomValidator ID="CustomValidator1" runat="server" 

            ControlToValidate="TextBox1" ErrorMessage="Invalid Zip Code" 

            onservervalidate="CustomValidator1_ServerValidate" 

            ValidationGroup="NewUserGroup"></asp:CustomValidator>
 

        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)

        {

            args.IsValid = true; //default, but set true anyway to illustrate the example
 

            if (DropDownList1.SelectedValue != "UnitedStates")

                return;
 

            System.Text.RegularExpressions.Regex regx = new System.Text.RegularExpressions.Regex(@"^\d{5}(-\d{4})?$"); //here is your zip code regex

            if (!regx.IsMatch(args.Value))  //args.Value contains the contents of the control you are validating. you could also just write TextBox1.Text, especially if you are validating several controls here

                args.IsValid = false;    //setting this false causes validation to fail so you will get the error message       

        }

Open in new window

0
 

Author Comment

by:VBBRett
Comment Utility
Hi, I tried to get this to work and nothing happened when I selected either different countries and nothing happened when I selected the united states.  When typing anything in the box whether it is correct format or incorrect format, nothing came to fruition.
0
 
LVL 16

Accepted Solution

by:
ororiole earned 500 total points
Comment Utility
This is a server side validator, it validates when the page postsback. click your submit button or whatever you use to submit and then it will validate and set the message for the error summary. If you want it to do client side  validation then you would write it in javascript, and enter the name of the javascript function in a property on the custom validator.

So now you have 3 options,
1. You could just disable the zip validator in the dropdown sel index changed event.
2. You can have it custom validate on the server and do all the checking in one place.
3. You can write a custom javascript routine and do all the checking there.
0
 

Author Comment

by:VBBRett
Comment Utility
How would I write the custom Javascript routine?  Can you help me out with how I can do this or do you need more information from me in order to get this handled?
0
 
LVL 16

Expert Comment

by:ororiole
Comment Utility
I can show you the skeleton. Then enter the name of the function in your custom validation control where the property is something like ClientValidationFunction. You will see it.

function ClientValidator(src, args)
{
  args.isvalid = false;
   //do your tests
  args.isvalid = true;
}

I am not a javascript guru so I dont know how to do the javascript for a regex. But if you post this:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = true; //default, but set true anyway to illustrate the example
 
            if (DropDownList1.SelectedValue != "UnitedStates")
                return;
 
            System.Text.RegularExpressions.Regex regx = new System.Text.RegularExpressions.Regex(@"^\d{5}(-\d{4})?$"); //here is your zip code regex
            if (!regx.IsMatch(args.Value))  //args.Value contains the contents of the control you are validating. you could also just write TextBox1.Text, especially if you are validating several controls here
                args.IsValid = false;    //setting this false causes validation to fail so you will get the error message      
        }
in the javascript zone and ASP.net zone again then someone can set you up.
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Suggested Solutions

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
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…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

763 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

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now