我有自定义验证属性:
public class RequireIfPropertyIsFalseAttribute : ValidationAttribute
{
private string basisProperty { get; set; }
public RequireIfPropertyIsFalseAttribute(string basisProperty)
{
this.basisProperty = basisProperty;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var basisProp = validationContext.ObjectType.GetProperty(basisProperty);
var isFalse = !(bool)basisProp.GetValue(validationContext.ObjectInstance, null);
if (isFalse)
{
if (value == null || (value.GetType() == typeof(string) && string.IsNullOrEmpty(((string)value).Trim())))
return new ValidationResult(this.ErrorMessage);
}
return ValidationResult.Success;
}
}
我将它用于两个模型属性:
public bool NoAgeProvided { get; set; }
[RequireIfPropertyIsFalse(nameof(NoAgeProvided), ErrorMessage = "This is required")]
[Display(Name = "Age")]
public int Age { get; set; }
public bool NoNameProvided { get; set; }
[RequireIfPropertyIsFalse(nameof(NoNameProvided), ErrorMessage = "This is required")]
[Display(Name = "Name")]
public string Name { get; set; }
验证后,名称验证消息显示"这是必需的"。但是,对于Age属性," Age字段是必需的"正在验证消息上显示。我究竟做错了什么? 如何显示设置的ErrorMessage?
答案 0 :(得分:1)
由于属性Age
属于int
,因此始终需要(int
不能为null
),如果您将文本框留空,则为{{1}提交值并首先执行必需的验证,并显示错误消息。
将您的财产更改为可以为空的
null
请注意,它适用于您的public int? Age { get; set; }
属性,因为它的Name
默认为可以为空。
作为旁注,您应该考虑实施string
,以便您也可以获得客户端验证。请参阅The Complete Guide To Validation In ASP.NET MVC 3 - Part 2。