FluentValidation传递参数

Chr*_*mut 3 c# validation fluentvalidation

我几小时前才发现FluentValidation,我想重写所有的验证逻辑,所以它只使用FV.

我有ATM的问题是我想使用来自输入的数据作为DomainExists()方法的参数.是否有可能或者我必须找到绕FV的方法才能实现这一目标?

    public QuoteValidator()
    {
    // hardcoded because don't know how to pass input string to RuleFor
        var inputeddomain = "http://google.com";

        RuleFor(r => r.Domain).NotEqual(DomainExists(inputeddomain));
    }

    // checks if inputeddomain is in repository (SQL DB)
    private string DomainExists(string inputeddomain)
    {
        var context = new QuoteDBContext().Quotes;
        var output = (from v in context
                     where v.Domain == inputeddomain
                     select v.Domain).FirstOrDefault();

        if (output != null) { return output; } else { return "Not found"; }
    }
Run Code Online (Sandbox Code Playgroud)

感谢@ bpruitt-goddard暗示,我得到了它的工作.这是我的问题的解决方案(希望它会帮助某人).

        public QuoteValidator()
    {
        RuleFor(r => r.Domain).Must(DomainExists).WithMessage("{PropertyValue} exists in system!");
    }

    private bool DomainExists(string propertyname)
    {
        var context = new QuoteDBContext().Quotes;
        var output = (from v in context
                      where v.Domain == propertyname
                      select v.Domain).FirstOrDefault();

        if (output != null) { return false; } else { return true; }
    }
Run Code Online (Sandbox Code Playgroud)

bpr*_*ard 7

您可以使用FluentValidation的Must方法从输入对象传入额外的数据.

RuleFor(r => r.Domain)
  .Must((obj, domain) => DomainExists(obj.InputDomain))
  .WithErrorCode("MustExist")
  .WithMessage("InputDomain must exist");
Run Code Online (Sandbox Code Playgroud)

虽然这样可行,但不建议在验证层中检查数据库是否存在,因为这是验证验证.相反,这种检查应该在业务层中完成.