使用 validateAllProperties = true
调用 Validator.TryValidateObject
时,我的自定义验证属性不会被触发。 ValidationResult
不包含我的错误属性值的条目。下面是用于测试的模型、属性和代码。
//Model
public class Model
{
[AmountGreaterThanZero]
public int? Amount { get; set; }
}
//Attribute
public sealed class AmountGreaterThanZero: ValidationAttribute
{
private const string errorMessage = "Amount should be greater than zero.";
public AmountGreaterThanZero() : base(errorMessage) { }
public override string FormatErrorMessage(string name)
{
return errorMessage;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
if ((int)value <= 0)
{
var message = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(message);
}
}
return null;
}
public override bool IsValid(object value)
{
if ((int)value < 0)
{
return false;
}
return true;
}
}
//Validation Code
var container = new Container();
container.ModelList = new List<Model>() { new Model() { Amount = -5 } };
var validationContext = new ValidationContext(container, null, null);
var validationResults = new List<ValidationResult>();
var modelIsValid = Validator.TryValidateObject(container, validationContext, validationResults, true);
注意:如果我使用 TryValidateProperty
方法,验证工作正常,并且 ValidationResult
返回正确的错误消息。
编辑:按照@Fals的建议和我采取的方法是单独验证列表中的每个对象。
最佳答案
将@Fals 的评论标记为答案,因为这是我最终采取的方法。因为没有其他问题的答案可以满足我原来的问题。
@Fals - Thats the problem, you must pass object by object to validade!
关于asp.net-mvc - MVC Validator.TryValidateObject 不验证自定义属性,validateAllProperties = true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17280213/