FluentValidator isEmpty 不验证第一项
我有一个流畅的验证器:
RuleFor(x => x.TypeTest)
.NotEmpty()
.WithMessage(x => string.Format(MessagesValidation.ValeurRequise, nameof(x.TypeTest)))
TypeTest 是枚举类型
public enum TypeTest
{
A,
B,
C,
}
- 即使我给出 TypeTest = "A" 验证器也不会验证它并返回错误。
- 解决方案,但我不喜欢它:
public enum TypeTest
{
Empty = 0,
A,
B,
C,
}
还有其他解决方案吗?请。
更新
问题是每当我给出第一个值时,它都会被视为空,并且验证器会返回错误。这就是为什么我添加一个新值作为 Empty 但我问是否还有其他方法?
I have a fluent validator:
RuleFor(x => x.TypeTest)
.NotEmpty()
.WithMessage(x => string.Format(MessagesValidation.ValeurRequise, nameof(x.TypeTest)))
TypeTest is enum type
public enum TypeTest
{
A,
B,
C,
}
- Even I give
TypeTest = "A"
validator doesn't valid it and return an error. - Solution but I didnt Like it:
public enum TypeTest
{
Empty = 0,
A,
B,
C,
}
is there any other solution ? please.
Updated
the problem is anytime I give the first value, it consider as Empty, and validator return an error. that is why I add a new value as Empty but im asking if there's an other way ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么要尝试使用 NotEmpty() 方法验证枚举类型?枚举永远不能为空。它总是有一个默认值。
如果要验证枚举类型的值,应该使用 IsInEnum() 方法。
此外,您不能像您在问题中所写的那样将字符串分配给枚举类型。
Why are you trying to validate an enum type using NotEmpty() method? Enum can never be empty. It always has a default value.
If you want to validate value of an enum type, you should use IsInEnum() method.
Also, you can't assign a string to an enum type as you've written in your question.
如果要
typeTest
允许“空”值,请使属性无效:应该使“ notempty()”验证器正常工作,但是缺点是为枚举介绍一个可能的值:<代码> null 。根据您的用例,可能需要
null
值。将属性的类型从typEtest
更改为typeTest?
将需要下游代码更改。任何依赖typeTest
属性的任何内容都需要使用x.typetest.value
而不仅仅是x.typetest
。If you want
TypeTest
to allow for "empty" values, make the property nullable:That should get the "NotEmpty()" validator working, but the downside is introducing an additional possible value for an enum:
null
. Depending on your use case, anull
value might be desirable. Changing the type of the property fromTypeTest
toTypeTest?
will require downstream code changes. Anything relying on theTypeTest
property will need to access the enum value usingx.TypeTest.Value
rather than justx.TypeTest
.