问题描述
我想检查 A 列和 B 列的组合在我的 blazor 应用程序中是否唯一。
使用 ValidationAttribute
public class MyClass
{
[IsUnique(ErrorMessage = "The entered value exists.")]
public string Code {get; set;}
}
public class IsUniqueAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value,ValidationContext validationContext)
{
var service = (DbService)validationContext.GetService(typeof(DbService))
bool exists = service.IsUnique((String)value);
if(exists == false)
{
return ValidationResult.Success;
}
return new ValidationResult(ErrorMessage,new[] { validationContext.MemberName });
}
}
但是,当涉及多个值时,我不知道如何做同样的事情。
假设我想检查以下 MyClass2
的代码 + 名称在数据库中是否唯一。
public class MyClass2
{
public string Code {get; set;}
public string Name {get;set;}
}
我尝试过使用自定义参数:
public class IsCodeNameCombinationUniqueAttribute : ValidationAttribute
{
public string Name{ get; set; }
public override bool IsValid(object value)
{
//Validate
}
}
public class MyClass2
{
[IsCodeNameCombinationUnique(ErrorMessage = "The combination of Code and Name exists.",Name = Name)]
public string Code {get; set;}
public string Name {get;set;}
}
不过好像只能把常量传给Name参数。
有什么方法可以制作自定义的 ValidationAttribute 来实现我想要的吗?
或者我应该使用自定义验证器? ( https://docs.microsoft.com/en-us/aspnet/core/blazor/forms-validation?view=aspnetcore-5.0#validator-components)
解决方法
您正在尝试的事情可以使用“类级别”验证来实现。
这可以通过在模型类中实现“IValidatableObject”并在“IValidatableObject”提供的“Validate”方法中提供验证逻辑来完成。
就你而言,
public class MyClass2 : IValidatableObject
{
public string Code {get; set;}
public string Name {get;set;}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var service = (DbService)validationContext.GetService(typeof(DbService))
bool exists = service.IsUniqueCombination(this.Code,this.Name);
if(exists)
{
yield return new ValidationResult("The combination of Code and Name exists.");
}
}
}