gpt4 book ai didi

c# - FluentValidation 传递参数

转载 作者:行者123 更新时间:2023-11-30 14:10:11 28 4
gpt4 key购买 nike

我在几个小时前才找到 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"; }
}

感谢@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; }
}

最佳答案

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

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

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

关于c# - FluentValidation 传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25312417/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com