Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><em>Note: I'm assuming you have AllowEmptyStrings = true because you're also using your view model outside of a web scenario; otherwise it doesn't seem like there's much of a point to having a Required attribute that allows empty strings in a web scenario.</em></p> <p>There are three steps to handle this:</p> <ol> <li>Create a custom attribute adapter which adds that validation parameter</li> <li>Register your adapter as an adapter factory</li> <li>Override the jQuery Validation function to allow empty strings when that attribute is present</li> </ol> <p><strong>Step 1: The custom attribute adapter</strong></p> <p>I modified the RequiredAttributeAdapter to add in that logic:</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace CustomAttributes { /// &lt;summary&gt;Provides an adapter for the &lt;see cref="T:System.Runtime.CompilerServices.RequiredAttributeAttribute" /&gt; attribute.&lt;/summary&gt; public class RequiredAttributeAdapter : DataAnnotationsModelValidator&lt;RequiredAttribute&gt; { /// &lt;summary&gt;Initializes a new instance of the &lt;see cref="T:System.Runtime.CompilerServices.RequiredAttributeAttribute" /&gt; class.&lt;/summary&gt; /// &lt;param name="metadata"&gt;The model metadata.&lt;/param&gt; /// &lt;param name="context"&gt;The controller context.&lt;/param&gt; /// &lt;param name="attribute"&gt;The required attribute.&lt;/param&gt; public RequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute) : base(metadata, context, attribute) { } /// &lt;summary&gt;Gets a list of required-value client validation rules.&lt;/summary&gt; /// &lt;returns&gt;A list of required-value client validation rules.&lt;/returns&gt; public override IEnumerable&lt;ModelClientValidationRule&gt; GetClientValidationRules() { var rule = new ModelClientValidationRequiredRule(base.ErrorMessage); if (base.Attribute.AllowEmptyStrings) { //setting "true" rather than bool true which is serialized as "True" rule.ValidationParameters["allowempty"] = "true"; } return new ModelClientValidationRequiredRule[] { rule }; } } } </code></pre> <p><strong>Step 2. Register this in your global.asax / Application_Start()</strong></p> <pre><code> protected void Application_Start() { AreaRegistration.RegisterAllAreas(); DataAnnotationsModelValidatorProvider.RegisterAdapterFactory(typeof(RequiredAttribute), (metadata, controllerContext, attribute) =&gt; new CustomAttributes.RequiredAttributeAdapter(metadata, controllerContext, (RequiredAttribute)attribute)); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); } </code></pre> <p><strong>Step 3. Override the jQuery "required" validation function</strong></p> <p>This is done using the jQuery.validator.addMethod() call, adding our custom logic and then calling the original function - you can read more about this approach <a href="http://blogs.teamb.com/craigstuntz/2009/01/15/37923/" rel="noreferrer">here</a>. If you are using this throughout your site, perhaps in a script file referenced from your _Layout.cshtml. Here's a sample script block you can drop in a page to test:</p> <pre><code>&lt;script&gt; jQuery.validator.methods.oldRequired = jQuery.validator.methods.required; jQuery.validator.addMethod("required", function (value, element, param) { if ($(element).attr('data-val-required-allowempty') == 'true') { return true; } return jQuery.validator.methods.oldRequired.call(this, value, element, param); }, jQuery.validator.messages.required // use default message ); &lt;/script&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload