如何在流利的验证中使用计算的属性

时间:2019-02-25 10:57:13

标签: c# asp.net fluentvalidation

我当前使用的是dto,其中包含以下几个字段:

public class Person
{
   public string FirstName { get; set; }
   public string LastName { get; set; } 
   //Other properties
}

我有上述dto的流利验证器。

我的问题是我如何单独为上述FirstNameLastName属性添加条件验证。验证应基于通过api调用获得的boolean属性(IsEnabled)。

我需要类似的东西

public class PersonValidator
{
    When(profileAdd => {**IsEnabled**}, () =>
    {
       //Validations for first name and last name
    }
}

我从github上了解到参数无法传递给验证器。那么,我该如何实现呢?

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

        When(x => IsEnabled, () => {
            // validation for first and last name
        });

或者这个:

RuleFor(person => person.FirstName).SetValidator(new YourCustomValidatior()).When(x => isEnabled);
RuleFor(person => person.LastName).SetValidator(new YourCustomValidatior()).When(x => isEnabled);

其中“ YourCustomValidator”将验证您的财产。 在此处了解有关自定义验证器表单的更多信息。 (https://fluentvalidation.net/custom-validators

您还可以使用内置验证器。 (https://fluentvalidation.net/built-in-validators