模型验证/ASP.NET MVC 3 - 有条件的必需属性 [英] Model Validation / ASP.NET MVC 3 - Conditional Required Attribute
问题描述
我的 ASP.NET MVC 3 应用程序有问题.我的模型中有 2 个属性,因此我只希望根据其中一个为空的情况在我的视图中需要其中的 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
并提供一个 Validate()
方法来实现你的自定义逻辑.如果您希望确保提供一个验证逻辑,请将其与客户端上的自定义验证逻辑结合起来.我发现这比实现属性更容易.
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屋!