Model Validation / ASP.NET MVC 3 - Conditional Required Attribute

僤鯓⒐⒋嵵緔 提交于 2019-11-27 18:02:09
tvanfosson

You can implement IValidatableObject on your class and provide a Validate() method that implements your custom logic. Combine this with custom validation logic on the client if you prefer to ensure that one is supplied. I find this easier than implementing an attribute.

public class ContactModel : IValidatableObject
{
   ...

   public IEnumerable<ValidationResult> Validate( ValidationContext context )
   {
        if (string.IsNullOrWhitespace( ContactPhoneNumber ) 
            && string.IsNullOrWhitespace( ContactEmailAddress ))
        {
             yield return new ValidationResult( "Contact Phone Number or Email Address must be supplied.", new [] { "ContactPhoneNumber", "ContactEmailAddress" } );
        }
   }
}

To get everything working at client side you'll need to add the following script to your view:

<script type="text/javascript">
$(function() {
    $('form').validate(); 
    $('form').rules('add', { 
        "ContactPhoneNumber": { 
            depends: function(el) { return !$('#ContactEmailAddress').val(); } 
        } 
    });
});
</script>

Annotation-based conditional validation can be defined using ExpressiveAnnotations:

[RequiredIf("ContactPhoneNumber == null",
    ErrorMessage = "At least email or phone should be provided.")]
public string ContactEmailAddress { get; set; }

[RequiredIf("ContactEmailAddress == null",
    ErrorMessage = "At least email or phone should be provided.")]
public string ContactPhoneNumber { get; set; }

I know you already have a solution, but I had a similar situation, so maybe my solution will prove helpful to someone else. I implemented a custom attribute with client-side validation. Here is my blog post: http://hobbscene.com/2011/10/22/conditional-validation/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!