何时&的FluentValidation必须? [英] FluentValidation for When & must?
问题描述
当dropdownlist值为yes
并且该字段必须为日期时,我正在尝试使用FluentValidation验证.当dropdownlist为yes
并检查date
时,它可以工作.但
当我选择No
时也显示验证,但仍然显示Must be date
.
I am trying use FluentValidation validaton when dropdownlist value is yes
and the field must be date. it is working when dropdownlist is yes
checking for date
. But
also showing validation when I select No
still it says Must be date
.
如果下拉列表值不是yes
,则不应再进行验证.我们该怎么做?
It should not validate anymore if dropdownlist value otherthan the yes
. How can we do that?
RuleFor(x => x.DtPublishedTimeText)
.NotEmpty()
.When(HasMaterialPublishedElseWhereText)
.WithMessage("Required Field")
.Must(BeAValidDate)
.WithMessage("Must be date");
private bool BeAValidDate(string val)
{
DateTime date;
return DateTime.TryParse(val, out date);
}
private bool HasMaterialPublishedElseWhereText(MeetingAbstract model)
{
return model.HasMaterialPublishedElseWhereText != null &&
model.HasMaterialPublishedElseWhereText.Equals("yes");
}
推荐答案
您遇到的问题是When
谓词仅适用于一条规则.您需要同时在NotEmpty
和Must
上进行条件验证.
The issue you are having is the When
predicate only applies to one rule. You need to have conditional validation on both the NotEmpty
AND the Must
.
有两种方法可以实现此目的.当只有几个条件规则时,选项1会比较整齐,否则我会使用选项2.
There two ways to achieve this. Option 1 is tidier when there are only a couple of conditional rules, otherwise I'd use option 2.
RuleFor(x => x.DtPublishedTimeText)
.NotEmpty()
.When(HasMaterialPublishedElseWhereText)
.WithMessage("Required Field")
.Must(BeAValidDate)
.When(HasMaterialPublishedElseWhereText)
.WithMessage("Must be date");
或
When(HasMaterialPublishedElseWhereText, () => {
RuleFor(x => x.DtPublishedTimeText)
.NotEmpty()
.WithMessage("Required Field");
RuleFor(x => x.DtPublishedTimeText)
.Must(BeAValidDate)
.WithMessage("Must be date");
});
请注意:我不知道HasMaterialPublishedElseWhereText
是什么还是它的外观.我假设您可以将其用作谓词
Do note: I have no idea what HasMaterialPublishedElseWhereText
is or what it looks like. I am assuming you can use it as a predicate
我还将考虑重构HasMaterialPublishedElseWhereText
方法,以下内容不太容易出错.
I'd also look at refactoring the HasMaterialPublishedElseWhereText
method, the following is less error prone.
private bool HasMaterialPublishedElseWhereText(MeetingAbstract model)
{
return String.Equals(model.HasMaterialPublishedElseWhereText, "yes", StringComparison.InvariantCultureIgnoreCase);
}
这篇关于何时&的FluentValidation必须?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!