Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp:RequiredFieldValidator does not validate hidden fields

Tags:

It seems that ASP.NET validators do not validate hidden fields. I get messages like this:

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

I have an <asp:HiddenField> in my page which gets filled client side with some value. I need this to be present once on the server so I added a RequiredFieldValidator to it.

And it does not work!

As I see it, as a workaround, I can:

1. use a custom validator and not tie it to the hidden field, just call a method on OnServerValidate;

2. Use a <asp:TextBox> with a CSS style display:none and it should work.

But I want to make sure I am not missing something here. Is it possible or not to validate a hidden field in the same way as the other text fields? O maybe a third, more elegant option?

TIA!

like image 430
meme Avatar asked Jul 07 '11 08:07

meme


2 Answers

@Peter's answer got me thinking, what does ControlPropertiesValid actually check??

Looking at the MSDN topic it looks for, among other things, the ValidationPropertyAttribute.. Hhmm, so if we just derive from HiddenField and decorate the new class with ValidationPropertyAttribute set to Value (for my purposes) then 'everything just works'. And it does.

using System.Web.UI; using System.Web.UI.WebControls;  namespace Partner.UserControls {     [ValidationProperty("Value")]     public class HiddenField2 : HiddenField {     } // nothing else required other than ValidationProperty } 

Usage - make sure you register the assembly containing the control:

<%@ Register Assembly="MyApp" Namespace="MyApp.Controls" TagPrefix="sw" %> 

And in your Page/UserControl content:

<sw:HiddenField2 ID="hidSomeImportantID" runat="server" /> 

All validators will work with this. The added benefit is that if you (like me) are using a custom validation function you can easily evaluate the HiddenField2.Value because it is contained in the args.Value field (on server side this is ServerValidateEventArgs).

like image 155
Scotty.NET Avatar answered Oct 26 '22 21:10

Scotty.NET


Just as the exception message you're getting says, it seems HiddenField controls can't be targeted by the standard validation controls directly. I would go with the CustomValidator workaround.

like image 24
Anders Fjeldstad Avatar answered Oct 26 '22 20:10

Anders Fjeldstad