c# - 自定义流利验证器

标签 c# fluentvalidation

我对使用 fluidvalidator 非常陌生。我所知道的只是基本的rulefor(),但是当涉及到自定义时我完全一无所知。有人可以指导我吗?

我需要验证可为空的 bool 属性。我需要比较 5 个 bool 属性,如果至少选择了其中之一,则它应该返回 true 且有效,否则,它应该返回 false 并提示一条错误消息,表明至少选择了其中之一。 以下是我想出的但不起作用的内容。

public class NullableValidator : AbstractValidator<bool>
{

    public bool isQualificationSet(tblNeutralFileMaint neutral)
    {
        if (neutral.MediationCivil==false && !neutral.CaseEvalCondemnation==false &&        neutral.MediationMagistrate==false && neutral.CaseEvalTorts==false && neutral.CaseEvalDomesticViolence==false)
            return false;
        else return true;
    }
} 

我这样使用它:

RuleFor(n => n.IsQualificationSet).SetValidator(new NullableValidator());

谁能告诉我怎么做?现在已经为此工作了几个小时。它没有显示任何错误,但不起作用或转到该方法。

最佳答案

我不完全确定我理解你想要做什么。您是否希望仅当 IsQualificationSet 属性设置为 true 时才执行此规则?我不明白 IsQualificationSet 和其他属性之间的关系。


无论如何,如果你想构建一个自定义属性验证器,那么它需要继承PropertyValidator基类(AbstractValidator用于验证顶级对象)。有关于此的文档可用 on the FV wiki )。

因此自定义属性验证器看起来像这样:

public class QualificationSetValidator : PropertyValidator {
    // Default error message specified in the base ctor
    // but it can be overriden using WithMessage in the RuleFor call
    public QualificationSetValidator() : base("At least one property must be selected.") {

    }

    protected override bool IsValid(PropertyValidatorContext context) {
        // You can retrieve a reference to the object being validated 
        // through the context.Instance property
        tblNeutralFileMaint neutral = (tblNeutralFileMaint)context.Instance;

        // You can also retrieve a reference to the property being validated
        // ...using context.PropertyValue

        // here is where you can do the custom validation
        // and return true/false depending on success.

     }
 }

作为定义自定义属性验证器类的替代方法,您还可以使用 PredicateValidator(“必须”方法)内嵌定义自定义规则 - 如果自定义逻辑很简单,这是一种更好的方法。有details on this in the documentation too .

关于c# - 自定义流利验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6706632/

相关文章:

c# - 选择 XML 节点

c# - 不同网络中两个应用程序之间的命令

asp.net-core - EditorFor Tag Helper 在使用 FluentValidator 时不呈现验证属性

c# - Fluent Validation 验证器在添加验证代码之前就会导致错误

c# - 外键的 FluentValidation RuleFor 属性

c# - 检查参数是否是具有流畅验证的 3 个值之一

c# - 如何确定哪个 DataRow 绑定(bind)到 DataGridViewRow

c# - 有没有办法用 C# 从另一个进程中删除关闭按钮?

c# - 在无限序列上创建 NUnit 测试

c# - C# 中 ValidationError 类的合理模式