我有一个具有 4 个字符串类型属性的模型。我知道您可以使用 StringLength 注释来验证单个属性的长度。但是我想验证 4 个属性的组合长度。
使用数据注释执行此操作的 MVC 方法是什么?
我问这个是因为我是 MVC 的新手,想在制定自己的解决方案之前以正确的方式进行操作。
最佳答案
您可以编写自定义验证属性:
public class CombinedMinLengthAttribute: ValidationAttribute
{
public CombinedMinLengthAttribute(int minLength, params string[] propertyNames)
{
this.PropertyNames = propertyNames;
this.MinLength = minLength;
}
public string[] PropertyNames { get; private set; }
public int MinLength { get; private set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var properties = this.PropertyNames.Select(validationContext.ObjectType.GetProperty);
var values = properties.Select(p => p.GetValue(validationContext.ObjectInstance, null)).OfType<string>();
var totalLength = values.Sum(x => x.Length) + Convert.ToString(value).Length;
if (totalLength < this.MinLength)
{
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
return null;
}
}
然后你可能有一个 View 模型并用它装饰它的一个属性:
public class MyViewModel
{
[CombinedMinLength(20, "Bar", "Baz", ErrorMessage = "The combined minimum length of the Foo, Bar and Baz properties should be longer than 20")]
public string Foo { get; set; }
public string Bar { get; set; }
public string Baz { get; set; }
}
关于c# - ASP.NET MVC : Custom Validation by DataAnnotation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16100300/