我有一个具有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; } }
然后您可能有一个视图模型,并用它来装饰其属性之一:
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; } }