我有一个具有4个字符串属性的模型。我知道可以使用StringLength注释验证单个属性的长度。然而,我想验证这4个属性的组合长度。
在MVC中,使用数据注释该如何实现呢?
我之所以提出这个问题,是因为我刚学习MVC,希望在自己想出解决方案之前找到正确的方法。
我有一个具有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; }
}
IsValid
时,validationContext
为空。你有什么想法我做错了什么吗? :-( - Grimm The Opiner你的模型应该实现 IValidatableObject
接口。将你的验证代码放在 Validate
方法中:
public class MyModel : IValidatableObject
{
public string Title { get; set; }
public string Description { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Title == null)
yield return new ValidationResult("*", new [] { nameof(Title) });
if (Description == null)
yield return new ValidationResult("*", new [] { nameof(Description) });
}
}
请注意:这是一种服务器端验证方式。它不适用于客户端,仅在表单提交后才会执行验证。
ExpressiveAnnotations提供了这样一个可能性:
[Required]
[AssertThat("Length(FieldA) + Length(FieldB) + Length(FieldC) + Length(FieldD) > 50")]
public string FieldA { get; set; }
要改进Darin的回答,可以稍微缩短一下:
public class UniqueFileName : ValidationAttribute
{
private readonly NewsService _newsService = new NewsService();
public override bool IsValid(object value)
{
if (value == null) { return false; }
var file = (HttpPostedFile) value;
return _newsService.IsFileNameUnique(file.FileName);
}
}
模型:
[UniqueFileName(ErrorMessage = "This file name is not unique.")]
请注意必须提供错误信息,否则错误将为空。
背景:
模型验证是必需的,以确保我们接收到的数据有效和正确,这样我们才能使用这些数据进行进一步处理。我们可以在操作方法中验证模型。内置的验证属性包括Compare、Range、RegularExpression、Required、StringLength。然而,在某些情况下,我们可能需要除内置属性之外的其他验证属性。
自定义验证属性
public class EmployeeModel
{
[Required]
[UniqueEmailAddress]
public string EmailAddress {get;set;}
public string FirstName {get;set;}
public string LastName {get;set;}
public int OrganizationId {get;set;}
}
public class UniqueEmailAddress : ValidationAttribute
{
private IEmployeeRepository _employeeRepository;
[Inject]
public IEmployeeRepository EmployeeRepository
{
get { return _employeeRepository; }
set
{
_employeeRepository = value;
}
}
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
var model = (EmployeeModel)validationContext.ObjectInstance;
if(model.Field1 == null){
return new ValidationResult("Field1 is null");
}
if(model.Field2 == null){
return new ValidationResult("Field2 is null");
}
if(model.Field3 == null){
return new ValidationResult("Field3 is null");
}
return ValidationResult.Success;
}
}
public string foo { get; set; }
public string bar { get; set; }
[MinLength(20, ErrorMessage = "too short")]
public string foobar
{
get
{
return foo + bar;
}
}
其实就是这样。如果你真的想在特定位置显示验证错误,可以在视图中添加以下内容:
@Html.ValidationMessage("foobar", "your combined text is too short")