我有以下 View 模型定义

public class AccessRequestViewModel
{
    public Request Request { get; private set; }
    public SelectList Buildings { get; private set; }
    public List<Person> Persons { get; private set; }
}

因此,在我的应用程序中,必须至少有1个人才能进行访问请求。您可以使用哪种方法进行验证?我不希望这种验证在我的 Controller 中发生,这很容易做到。唯一选择是自定义验证属性吗?

编辑:当前使用FluentValidation执行此验证(漂亮的库!)
RuleFor(vm => vm.Persons)
                .Must((vm, person) => person.Count > 0)
                .WithMessage("At least one person is required");

最佳答案

如果使用数据注释执行验证,则可能需要一个自定义属性:

public class EnsureOneElementAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var list = value as IList;
        if (list != null)
        {
            return list.Count > 0;
        }
        return false;
    }
}

接着:
[EnsureOneElement(ErrorMessage = "At least a person is required")]
public List<Person> Persons { get; private set; }

或使其更通用:
public class EnsureMinimumElementsAttribute : ValidationAttribute
{
    private readonly int _minElements;
    public EnsureMinimumElementsAttribute(int minElements)
    {
        _minElements = minElements;
    }

    public override bool IsValid(object value)
    {
        var list = value as IList;
        if (list != null)
        {
            return list.Count >= _minElements;
        }
        return false;
    }
}

接着:
[EnsureMinimumElements(1, ErrorMessage = "At least a person is required")]
public List<Person> Persons { get; private set; }

我个人使用FluentValidation.NET而不是数据注释来执行验证,因为我更喜欢命令式验证逻辑而不是声明式。我认为它更强大。因此,我的验证规则将如下所示:
RuleFor(x => x.Persons)
    .Must(x => x.Count > 0)
    .WithMessage("At least a person is required");

10-05 21:07
查看更多