简体   繁体   English

使用 Fluent Validation 如何检查对象中的两个属性都不能有值?

[英]Using Fluent Validation how can I check that two properties in an object both can't have a value?

I want to validate two properties ( MyProperty1 , MyProperty2 ) in a class.我想验证一个类中的两个属性( MyProperty1MyProperty2 )。 These properties can both be null.这些属性都可以为空。 They both have separate validation rules but they cannot both have a value set.它们都有单独的验证规则,但它们不能都有一个值集。

public MyObject 
{
    public string MyProperty1 { get; set; }
    public string MyProperty2 { get; set; }
}

I am trying to avoid writing something like this我试图避免写这样的东西

            When(
            c => c.MyProperty1 != null && c.MyProperty2 != null,
            () =>
                this.RuleFor(r => r.MyProperty1 )
                    .Null()
                    .WithMessage("MyProperty1 must be null when MyProperty2 has value"));

The following will achieve that and keeps the fluent readability.以下将实现这一点并保持流畅的可读性。

RuleFor(o => o.MyProperty1)
    .Null()
    .When(o => o.MyProperty2 != null)
    .WithMessage("MyProperty1 must be null when MyProperty2 has value");

RuleFor(o => o.MyProperty2)
    .Null()
    .When(o => o.MyProperty1 != null)
    .WithMessage("MyProperty2 must be null when MyProperty1 has value");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何创建一个忽略没有setter的属性的Fluent NHibernate约定 - How can I create a Fluent NHibernate Convention that ignores properties that don't have setters 我可以在流利的验证器中使用验证器吗 - Can I have validators inside validators with fluent validation 我如何串联两个不同的列表 <T> 两者都有相同的基类? - How can i concatenate two different list<T> where both have same base class? 如何使两个属性的验证属性MVC - How can I make validation attribute MVC for two properties 如何写出“流利的”日期时间值? - How can I write a “fluent” datetime value? 我如何合并两个对象的类和通用列表 <T> 使用LINQ - How can i merge two object both Class and Generic List<T> use LINQ 如何仅初始化具有值的属性? - How can I initialize only properties that have a value? 如何使用 C# 检查对象(我必须插入到列表中)是否已经在列表中? - How can I check if an object (that I have to insert in a list) is already in the list using C#? 如何为两个复选框设置不同的事件? - How I can have different events for two check boxes? 如何获得失败的xsd验证的实际对象值 - how can I get the actual object value of a failed xsd validation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM