Friday, April 5, 2013

Validate asp:HiddenField Value with asp.net validators

One of the things I ran across while developing an asp.net 2.0 Website was having to validate a hidden field with a required and a regular expression validator due to a requirement that my client requested.

At first I thought I was missing some property when I started to debug the website. I would get the error

Control 'hiddenField' referenced by the ControlToValidate property of 'hiddenFieldValidator' cannot be validated.

So after some further research I found that Microsoft has decided that you should never need to validate a hidden field, and hence the problem and error above.

Now there are obviously different ways to solve for this but for my purposes the simplest was to create an inherited HiddenField control which would allow the validation.

I got the solution from a stack overflow post here and modified it ever so slightly to get it working for me.

First thing that you will need is to add a new class under the App_Code folder of the Website. If you do not see this folder, don't despair it is quite simple to add. Just right click on the website in solution explorer and go down to Add -> Add ASP.NET Folder -> App_Code. Now you should have the folder and you are ready for the next step. If you already have other classes within that folder it should be simple to add a new class the add the following code with it.

Great! now that you have a new control you need to register it within the website to be able to use it within your asp.net website. Open your web.config file and locate the "pages" section. Then add a new register tag for your control like so

Notice that the namespace is the same as what we declared in our class earlier and that the assembly it is generated in resides within App_Code. Now save and build your website so that the assemblies are ready and next you can start using your new control! You can use it anywhere in your Website with the following markup

Now when I compile and build the website it is able to run the validation against the hidden control and all the behaviors are as expected.

No comments:

Post a Comment