英文:
With FluentValidation check that one are more property are populated
问题
使用FluentValidation,我需要验证五个属性中至少有一个已填充。假设我有以下类:
public class Something
{
public string Required1 { get; set; }
public string Required2 { get; set; }
public string Optional1 { get; set; }
public string Optional2 { get; set; }
public string Optional3 { get; set; }
public string Optional4 { get; set; }
public string Optional5 { get; set; }
}
然后我有一个验证器,具有以下构造函数:
public SomethingValidator()
{
RuleFor(e => e.Required1)
.NotEmpty();
RuleFor(e => e.Required2)
.NotEmpty();
RuleFor(e => e.Required1)
.Must((e, r1) =>
!string.IsNullOrWhiteSpace(e.Optional1)
|| !string.IsNullOrWhiteSpace(e.Optional2)
|| !string.IsNullOrWhiteSpace(e.Optional3)
|| !string.IsNullOrWhiteSpace(e.Optional4)
|| !string.IsNullOrWhiteSpace(e.Optional5)
);
}
它可以工作,但似乎有点奇怪,我向属性添加规则,而实际上我想要的是一个针对整个对象的规则。第三个RuleFor()
中表达的属性可以是任何属性。它在Must()
方法中不是必需的。
是否有更好的内置规则类型?
英文:
With FluentValidation I need to validate that at lest one of five properties is populated. Lets say I have this class:
public class Something
{
public string Required1 { get; set; }
public string Required2 { get; set; }
public string Optional1 { get; set; }
public string Optional2 { get; set; }
public string Optional3 { get; set; }
public string Optional4 { get; set; }
public string Optional5 { get; set; }
}
Then I have a validator with this constructor:
public SomethingValidator()
{
RuleFor(e => e.Required1)
.NotEmpty();
RuleFor(e => e.Required2)
.NotEmpty();
RuleFor(e => e.Required1)
.Must((e, r1) =>
!string.IsNullOrWhiteSpace(e.Optional1)
|| !string.IsNullOrWhiteSpace(e.Optional2)
|| !string.IsNullOrWhiteSpace(e.Optional3)
|| !string.IsNullOrWhiteSpace(e.Optional4)
|| !string.IsNullOrWhiteSpace(e.Optional5)
);
}
It works but it seem kinda funky that I'm add a rule to a property when really I want a rule just for the object. The property express in the third RuleFor()
could be anything. It's not required in the Must()
method.
Is there a better built in rule type?
答案1
得分: 0
你可以从RuleFor(e => e)
开始时省略该属性,只需传递目标对象。
RuleFor(e => e)
.Must(e =>
!string.IsNullOrWhiteSpace(e.Optional1)
|| !string.IsNullOrWhiteSpace(e.Optional2)
|| !string.IsNullOrWhiteSpace(e.Optional3)
|| !string.IsNullOrWhiteSpace(e.Optional4)
|| !string.IsNullOrWhiteSpace(e.Optional5)
);
英文:
You can ommit that property when you start from RuleFor(e => e)
just passing the target object.
RuleFor(e => e)
.Must(e =>
!string.IsNullOrWhiteSpace(e.Optional1)
|| !string.IsNullOrWhiteSpace(e.Optional2)
|| !string.IsNullOrWhiteSpace(e.Optional3)
|| !string.IsNullOrWhiteSpace(e.Optional4)
|| !string.IsNullOrWhiteSpace(e.Optional5)
);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论