English 中文(简体)
认证 ASP.NET MVC 3 - 各项条件要求
原标题:Model Validation / ASP.NET MVC 3 - Conditional Required Attribute

我与我的协会有麻烦。 NET MVC 3 application. 我的模型有2个特性,根据这个模式,我只想其中1个,我认为这1个是空的。 例如,如果我进入电话号码,那么电子邮件就不再需要,反之亦然。

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

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

我是否需要建立一种习俗归属,以验证我的模式,如果是,我如何做到这一点?

最佳回答

页: 1 目标关于您的类别,并提供符合您习惯逻辑的<代码>Validate(>方法。 如果你倾向于确保提供一种服务,则按客户的习俗验证逻辑确定这一点。 我认为,这比执行一个特性更容易。

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" } );
        }
   }
}

为了在客户方面进行一切工作,你认为有必要在你看来添加以下文字:

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




相关问题
Using jquery to get a partial view and updating the UI

I need to render a partial view (returned from the controller) to show some customer summary details. This will need to happen when the user clicks on a button. In the the mean time the user can ...

MVC 2 / MVC 3 / MVC 4

MVC 2 我们可以轻松地创造领域。 现在,我的问题涉及nes地区(地区内)。

Asp.Net MVC 2 - Changing the PropertyValueRequired string

Using a resx file in the App_GlobalResources directory, I ve been able to change the default message for the PropertyValueInvalid string of the model validators. But it doesn t work to translate the ...

ASP.NET MVC 3 - What features do you want to see? [closed]

I know a bunch of people that are really enjoying the improvements that ASP.NET MVC 2 made over the first release. I have just started to migrate our MVC 1 project over and so far areas has totally ...

热门标签