<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Validation - Greg Shackles]]></title><description><![CDATA[Validation - Greg Shackles]]></description><link>https://gregshackles.com/</link><image><url>https://gregshackles.com/favicon.png</url><title>Validation - Greg Shackles</title><link>https://gregshackles.com/</link></image><generator>Ghost 4.32</generator><lastBuildDate>Sat, 23 May 2026 10:42:47 GMT</lastBuildDate><atom:link href="https://gregshackles.com/tag/validation/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Validating Hidden Fields in ASP.NET MVC 2]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>One of the many nice things they have added in MVC 2 is model/view model validation on both the client and server side.  I won&#x2019;t go into the basics here since they have been covered extensively by others.  However, recently I was adding validation to require a</p>]]></description><link>https://gregshackles.com/validating-hidden-fields-in-asp-net-mvc-2/</link><guid isPermaLink="false">61ce48a0437e8200017d40f6</guid><category><![CDATA[ASP.NET]]></category><category><![CDATA[MVC]]></category><category><![CDATA[Validation]]></category><dc:creator><![CDATA[Greg Shackles]]></dc:creator><pubDate>Sun, 21 Feb 2010 14:00:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>One of the many nice things they have added in MVC 2 is model/view model validation on both the client and server side.  I won&#x2019;t go into the basics here since they have been covered extensively by others.  However, recently I was adding validation to require a value for a hidden field on a form, and found that the default validation functionality just didn&#x2019;t work on the client side for a hidden field.  Here I will go over how I added some custom validation to allow me to do it.</p>
<p>While it might sound weird to validate a hidden field, something a user will never directly interact with, in this age of complex interfaces built in JavaScript it&#x2019;s easy to imagine a scenario where a series of interactions leads to storing some kind of value in a hidden field.  If that end value is something that is required, it&#x2019;s only natural that that should be enforced by the model.</p>
<p>First, let&#x2019;s start by defining a very simple view model for the form:</p>
<pre><code class="language-language-csharp">public class DemoForm
{
    [Required(ErrorMessage = &quot;You must enter a name&quot;)]
    public string Name { get; set; }
}
</code></pre>
<p>It just defines a single property for storing a name.  Now we can define a very basic view that is strictly typed to that view model.  Here is the code for setting up the form:</p>
<pre><code class="language-language-aspnet">&lt;% using (Html.BeginForm())
{ %&gt;

    &lt;%= Html.HiddenFor(model =&gt; model.Name) %&gt;

    &lt;p&gt;
        &lt;%= Html.ValidationMessageFor(model =&gt; model.Name) %&gt;
    &lt;/p&gt;

    &lt;input type=&quot;submit&quot; value=&quot;Submit&quot; /&gt;

&lt;% } %&gt;
</code></pre>
<p><img src="https://gregshackles.com/content/images/2014/12/validation1.png" alt="Page output" loading="lazy"></p>
<p>If you run the page now, you will get correct server-side validation, but nothing on the client.  To get client validation in MVC, we need to tell the page to enable client validation.  To do that, call this before starting the form:</p>
<pre><code class="language-language-aspnet">&lt;% Html.EnableClientValidation(); %&gt;
</code></pre>
<p>You will also need some JavaScript references to these files, which are included by default in any new MVC project:</p>
<pre><code class="language-language-aspnet">&lt;script type=&quot;text/javascript&quot; src=&quot;&lt;%= ResolveUrl(&quot;~/Scripts/MicrosoftAjax.js&quot;) %&gt;&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;&lt;%= ResolveUrl(&quot;~/Scripts/MicrosoftMvcAjax.js&quot;) %&gt;&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;&lt;%= ResolveUrl(&quot;~/Scripts/MicrosoftMvcValidation.js&quot;) %&gt;&quot;&gt;&lt;/script&gt;
</code></pre>
<p>Now if you reload the page, client validation still isn&#x2019;t working.  Why not?  After digging through the Microsoft validation scripts a bit, I found that the Required validator ignores hidden fields altogether in JavaScript.  We could change it from being a hidden field to a text field and the same code would work as expected, but that&#x2019;s not what we want to do.</p>
<p>As it turns out, they made it rather simple to extend the built-in validation with your own custom rules.  First, we&#x2019;ll define the attribute class, so that it can be added as a decorator to a property the same way the other validators work.  In this case, since the Required attribute actually works fine on the server side, our class will extend that and do nothing else.  This way we can provide the client side functionality and rely on the existing server validation.</p>
<pre><code class="language-language-csharp">public class HiddenRequiredAttribute : RequiredAttribute
{
}
</code></pre>
<p>Now that we have the attribute, we need a validator that uses it.  To do that, we extend the DataAnnotationsModelValidator class, and tell it to use the attribute we just defined:</p>
<pre><code class="language-language-csharp">public class HiddenRequiredValidator : DataAnnotationsModelValidator&lt;HiddenRequiredAttribute&gt;
{
    private string _errorMessage;

    public HiddenRequiredValidator(ModelMetadata metaData, ControllerContext context, HiddenRequiredAttribute attribute)
        : base(metaData, context, attribute)
    {
        _errorMessage = attribute.ErrorMessage;
    }

    public override IEnumerable&lt;ModelClientValidationRule&gt; GetClientValidationRules()
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = _errorMessage,
            ValidationType = &quot;hiddenRequired&quot;
        };

        return new[] { rule };
    }
}
</code></pre>
<p>The important part to notice here is where we set the ValidationType to &#x201C;hiddenRequired.&#x201D;  This is the unique identifier we define for referencing our validator in JavaScript.  Remember it, because you&#x2019;re going to need it later.</p>
<p>So now we have an attribute, and a validator for it.  Next up, we need to register our validator in the application&#x2019;s Application_Start function:</p>
<pre><code class="language-language-csharp">DataAnnotationsModelValidatorProvider
    .RegisterAdapter(typeof(HiddenRequiredAttribute), typeof(HiddenRequiredValidator));
</code></pre>
<p>Now let&#x2019;s switch the view model&#x2019;s Name property to use the new HiddenRequired attribute instead of the Required one we had before:</p>
<pre><code class="language-language-csharp">public class DemoForm
{
    [HiddenRequired(ErrorMessage = &quot;You must enter a name&quot;)]
    public string Name { get; set; }
}
</code></pre>
<p>All that remains is to put in some JavaScript code to handle the validation.  I&#x2019;ll show the code here, and then discuss it.  Since this is a contained demo, I will add the code directly to the view.</p>
<pre><code class="language-language-javascript">Sys.Mvc.ValidatorRegistry.validators[&quot;hiddenRequired&quot;] = function(rule)
{
    return function(value, context)
    {
        if (value)
        {
            return true;
        }

        return rule.ErrorMessage;
    }
};
</code></pre>
<p>If that code looks simple, that&#x2019;s because it is.  Since we&#x2019;re only validating that the field has some kind of value, that is all we need to check for.  The reason that the return function is wrapped in another function is to allow for adding more complex logic before the return function if needed.  For this example, it isn&#x2019;t needed.</p>
<p><img src="https://gregshackles.com/content/images/2014/12/validation2.png" alt="Updated page output" loading="lazy"></p>
<p>Now if you reload the page you will get the client-side validation we were aiming for, triggered by the submit button.  Always remember that client-side validation is just there for improving the user experience, and is no substitute for server validation.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item></channel></rss>