本文介绍了ASP.NET MVC:自定义验证通过DataAnnotation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有4个属性这是一个字符串类型的模型。我知道你可以通过使用StringLength注解验证一个属性的长度。不过,我要验证的4个属性组合的长度。
I have a Model with 4 properties which are of type string. I know you can validate the length of a single property by using the StringLength annotation. However I want to validate the length of the 4 properties combined.
什么是MVC的方式与数据注解做到这一点?
What is the MVC way to do this with data annotation?
我问这个,因为我是新来的MVC,并希望让我自己的解决方案之前,做了正确的道路。
I'm asking this because I'm new to MVC and want to do it the correct way before making my own solution.
推荐答案
您可以编写一个自定义的验证属性:
You could write a custom validation attribute:
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;
}
}
,然后你可能有一个视图模型和装饰它的一个属性与它:
and then you might have a view model and decorate one of its properties with it:
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; }
}
这篇关于ASP.NET MVC:自定义验证通过DataAnnotation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!