首页 > 解决方案 > Fluent Validation,在编辑模式下,需要在属性更改时触发规则

问题描述

在编辑值时,如果 property2 的值​​发生更改,我必须验证 property1。

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public PersonType PersonType { get; set; }
    public bool IsVIP { get; set; }
}

public enum PersonType
{
    VIP,
    AnyType1,
    AnyType2
}

public class PersonValidator : AbstractValidator<Person>
{
    public PersonValidator()
    {
        RuleFor(x => x.PersonType).Must(CantChangePersonTypeForVIP);
    }

    private bool CantChangePersonTypeForVIP(Person person, PersonType arg)
    {
        // even if PersonType was not changed this method will call and a VIP person validation will always fail
        if (person.IsVIP)
        {
            return false;
        }
        return true;
    }
}

如评论中所述,即使 PersonType 未更改,此方法也会调用并且 VIP 人员验证将始终失败。

我该如何实施?理想情况下,我期望如果 PersonType 在编辑时没有更改,它就不会调用。

我不知道如何实现这一点。

我是否应该点击 DB 来比较原始对象?

标签: c#asp.net-coreasp.net-web-apifluentvalidation

解决方案


推荐阅读