【问题标题】:How to use a computed property in fluent validation如何在流畅的验证中使用计算属性
【发布时间】:2019-02-25 10:57:13
【问题描述】:

我目前正在使用具有以下几个字段的 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 读到参数不能传递给验证器。那么,我该如何实现呢?

【问题讨论】:

  • 你可以使用 Must...RuleFor(r => propertyname) .Must((obj, i) => CheckIsEnable()) .WithMessage("Error");

标签: c# asp.net fluentvalidation


【解决方案1】:

你可以试试这个:

        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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多