简体   繁体   English

如何使用FluentValidation有条件地验证属性?

[英]How to conditionally validate properties using FluentValidation?

I'm trying to implement a rule using FluentValidation where two properties have a dependency on each other. 我正在尝试使用FluentValidation实施规则,其中两个属性相互依赖。 They are Unit and UnitType . 它们是UnitUnitType Unit is a string, and UnitType is an enum. Unit是一个字符串,而UnitType是一个枚举。 I want rules where if the Unit is filled out then the UnitType cannot be None (0) , and if the UnitType is not None (0) then the Unit must be filled out. 我想要一个规则,如果填写Unit ,则UnitType不能为None (0) ,如果UnitType不是None (0)则必须填写Unit Here's the rules I've tried so far to no avail: 到目前为止,我尝试过的规则毫无用处:

this.RuleFor(
    p =>
        p.Unit).NotEmpty().When(
    l =>
        (l.UnitType != UnitType.None)).WithMessage("Unit № must be filled out and must be less than 8 characters long when the Unit Type is selected");

this.RuleFor(
    p =>
        p.UnitType).NotEqual(UnitType.None).When(
    l =>
        !String.IsNullOrEmpty(l.Unit)).WithMessage("Unit Type must be selected when the Unit № is filled out");

No matter how I tweak the rules, I just keep getting an error that says: 'Unit Type' must not be empty. 无论我如何调整规则,我都会不断收到一条错误消息: “单元类型”不能为空。 Since my custom error messages are not showing up, I'm thinking that the rules are being skipped somehow... 由于未显示我的自定义错误消息,因此我认为规则以某种方式被跳过了...

I'd appreciate any suggestions on how to get this fixed. 如果您有关于如何解决此问题的任何建议,我将不胜感激。

Well, after taking some time away from this and coming back to it, I believe I finally have it resolved. 好吧,在花了一些时间再回到它之后,我相信我终于解决了它。 Originally in my post model I had the UnitType property as non-nullable, which is what was triggering the validation even though it's default value was UnitType.None . 最初在我的帖子模型中,我将UnitType属性设置为不可为空,即使默认值是UnitType.None ,这也是触发验证的UnitType.None From what I can tell, MVC, not FluentValidation, sees that it's non-nullable property, ignores the default value and then attempts to bind the property anyway with a null value from the form post. 据我所知,MVC 而不是 FluentValidation看到它是不可为空的属性,它会忽略默认值,然后无论如何都尝试使用表单发布中的空值绑定该属性。 I can kind of understand why it behaves this way, but can't help but think that it shouldn't ignore default values. 我可以理解为什么它会以这种方式运行,但是不禁认为它不应该忽略默认值。

So, I changed the property to be nullable and now my two rules work as I expect them to. 因此,我将该属性更改为可为空,现在我的两个规则可以按预期工作。 Still, I'm not overly happy about the way it actually works because I was hoping to use the default auto-generated value further down when mapping with AutoMapper, and now I'll have to make sure to set a default value in the constructor where it's relevant. 不过,对于它的实际工作方式,我还是不太满意,因为我希望在使用AutoMapper映射时进一步使用默认的自动生成的值,现在我必须确保在构造函数中设置默认值相关的地方。 Realistically a non-issue in the long run, so long as I don't miss setting a default somewhere. 从长远来看,实际上是没有问题的,只要我不要错过在某个地方设置默认值即可。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM