asp:RequiredFieldValidator does not validate hidden fields asp:RequiredFieldValidator does not validate hidden fields asp.net asp.net

asp:RequiredFieldValidator does not validate hidden fields


@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).


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.


Here is the workaround I came up with, because unfortunately I couldn't find any reliable way to validate using the RequiredFieldValidator OR the CustomValidator out of the box. If you leave the ControlToValidate property empty it yells at you. All you have to do is create a custom control like the one below:

public class HiddenFieldValidator : RequiredFieldValidator{    protected override bool ControlPropertiesValid()    {        return true;    }}

By overriding the properties valid check so that it always returns true it no longer cares that you are using a HiddenField and it will pull the value out of it and verify without issue.