模型验证/ ASP.NET MVC 3 - 条件要求的属性 [英] Model Validation / ASP.NET MVC 3 - Conditional Required Attribute

查看:176
本文介绍了模型验证/ ASP.NET MVC 3 - 条件要求的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的ASP.NET MVC 3应用程序的麻烦。我有2 propertiesin我的模型,即我只基于哪一个是空的希望他们的1在我看来必需的。因此,例如,如果我输入一个电话号码,然后邮件不再需要,反之亦然,但如果我离开这两个空的,则是1应该是必需的,下面是我的模型:

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 for example, if I enter a phone number then email is no longer required and vice versa, but if I leave both empty, then either 1 should be required, below is my model:

[Display(Name = "Contact Phone Number:")]
[MaxLength(150)]
public string ContactPhoneNumber { get; set; }

[Display(Name = "Contact Email Address:")]
[MaxLength(100)]
public string ContactEmailAddress { get; set; }

我会需要创建一个自定义属性来验证我的模型,如果是这样,我将如何实现这一目标?

Would I need to create a custom attribute to validate my model and if so, how would I achieve this?

推荐答案

您可以实施 IValidatableObject 在你的类,并提供了一​​个验证()实现您的自定义逻辑方法。使用自定义的验证逻辑在客户端上结合这个,如果你preFER以确保一个提供。我觉得这比实现一个属性更容易。

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>

这篇关于模型验证/ ASP.NET MVC 3 - 条件要求的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆