检查属性在 FluentValidation 的列表中是否唯一
本文关键字:是否 唯一 列表 属性 FluentValidation 检查 | 更新日期: 2023-09-27 18:31:52
我试图确保列表具有唯一的SSN。我收到"无法自动确定表达式元素 => 元素的属性名称。请通过调用"WithName"错误来指定自定义属性名称。我们会知道我在这里做错了什么吗?
using FluentValidation;
using FluentValidation.Validators;
public class PersonsValidator : AbstractValidator<Persons>
{
public PersonsValidator()
{
this.RuleFor(element => element)
.SetValidator(new SSNNumbersInHouseHoldShouldBeUnique<Persons>())
.WithName("SSN");
.WithMessage("SSN's in household should be unique");
}
}
public class SSNNumbersInHouseHoldShouldBeUnique<T> : PropertyValidator
{
public SSNNumbersInHouseHoldShouldBeUnique()
: base("SSN's in household should be unique")
{
}
protected override bool IsValid(PropertyValidatorContext context)
{
var persons = context.Instance as Persons;
try
{
if (persons == null)
{
return false;
}
var persons = persons.Where(element => element.SSN.Trim().Length > 0);
var allSSNs = persons.Select(element => element.SSN.Trim());
if (allSSNs.Count() > allSSNs.Distinct().Count())
{
return false;
}
return true;
}
catch (Exception ex)
{
return false;
}
}
}
public class Persons : List<Person>
{}
public class Person
{
public string SSN{ get; set; }
}
我使用的是FluentValidation 4.6版本。根据Jeremy Skinner(FluentValidation的作者)的说法,我需要至少使用5.6才能使用模型级规则(如RuleFor(element => element))。作为一种解决方法,我在实际类本身上添加了此验证,而不是创建验证类。希望这对某人有所帮助。
using FluentValidation;
using FluentValidation.Results;
public class Persons : List<Person>
{
public void ValidateAndThrow()
{
var errors = new List<ValidationFailure>();
try
{
var persons = this.Where(element => element.SSN.Trim().Length > 0);
var allSSNs = persons.Select(element => element.SSN.Trim());
if (allSSNs.Count() > allSSNs.Distinct().Count())
{
var validationFailure = new ValidationFailure("UniqueSSNsInHouseHold", "SSN's in a household should be unique");
errors.Add(validationFailure);
}
}
catch (Exception ex)
{
}
if (errors.Any())
{
throw new ValidationException(errors);
}
}
}