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

前端 未结 4 927
温柔的废话
温柔的废话 2020-12-04 16:51

I\'m having trouble with my ASP.NET MVC 3 application. I have 2 propertiesin my model whereby I only want 1 of them required in my view based on whichever one is empty. So f

4条回答
  •  时光说笑
    2020-12-04 17:43

    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 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:

    
    

提交回复
热议问题