![](/img/trans.png)
[英]FluentValidation - Check value is an expression only if the value is not null
[英]FluentValidation how to check for Length if string is not null?
我用两个string
测试PUT
:
company.CurrencyCode = request.CurrencyCode ?? company.CurrencyCode;
company.CountryIso2 = request.Country ?? company.CountryIso2;
我尝试过如下规则:
public UpdateCompanyValidator()
{
RuleSet(ApplyTo.Put, () =>
{
RuleFor(r => r.CountryIso2)
.Length(2)
.When(x => !x.Equals(null));
RuleFor(r => r.CurrencyCode)
.Length(3)
.When(x => !x.Equals(null));
});
}
因为我不介意在这些属性上获取null
,但我想在属性不为null
时测试Length
。
当属性可以为nullable
时应用规则的最佳方法是什么,我们只想测试它是否为空?
其中一种方式是:
public class ModelValidation : AbstractValidator<Model>
{
public ModelValidation()
{
RuleFor(x => x.Country).Must(x => x == null || x.Length >= 2);
}
}
我更喜欢以下语法:
When(m => m.CountryIso2 != null,
() => {
RuleFor(m => m.CountryIso2)
.Length(2);
);
对我来说最好的语法:
RuleFor(t => t.DocumentName)
.NotEmpty()
.WithMessage("message")
.DependentRules(() =>
{
RuleFor(d2 => d2.DocumentName).MaximumLength(200)
.WithMessage(string.Format(stringLocalizer[""message""], 200));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.