用于验证的数据注释,至少有一个必填字段?
如果我有一个包含字段列表的搜索对象,我可以使用 System.ComponentModel.DataAnnotations 命名空间将其设置为验证搜索中至少有一个字段不为 null 或空吗?即所有字段都是可选的,但至少应输入一个字段。
If I have a search object with a list of fields, can I, using the System.ComponentModel.DataAnnotations namespace, set it up to validate that at least one of the fields in the search is not null or empty? i.e All the fields are optional but at least one should always be entered.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我扩展了 Zhaph 答案以支持属性分组。
用法:
如果你想有 2 组(或更多):
I have extended Zhaph answer to support grouping of properties.
Usage:
And if you want to have 2 groups (or more):
我会为此创建一个自定义验证器 - 它不会为您提供客户端验证,而只会为您提供服务器端验证。
请注意,要使其工作,您需要使用
nullable
类型,因为值类型默认为0
或false
:首先创建一个新的验证器:
然后,您可以用以下方法装饰您的模型:
然后,当您调用 ModelState.IsValid 时,您的验证器将被调用,并且您的消息将被添加到视图上的 ValidationSummary 中。
请注意,您可以扩展它来检查返回的属性类型,或者如果您愿意的话,可以查找它们的属性以包含/排除验证 - 这是假设一个通用验证器不知道它正在验证的类型的任何信息。
I'd create a custom validator for this - it won't give you client side validation, just server side.
Note that for this to work, you'll need to be using
nullable
types, as value types will default to0
orfalse
:First create a new validator:
You can then decorate your models with this:
Then when you call
ModelState.IsValid
your validator will be called, and your message will be added to the ValidationSummary on your view.Note that you could extend this to check for the type of property coming back, or look for attributes on them to include/exclude from validation if you want to - this is assuming a generic validator that doesn't know anything about the type it's validating.
这个问题已经很老了,但是从.NET 3.5(我相信)开始,IValidatableObject 可以帮助解决棘手的验证情况。您可以实现它来验证任意业务规则。在这种情况下,类似:
This question is pretty old, but as of .NET 3.5 (I believe), IValidatableObject can help with tricky validation situations. You can implement it to validate arbitrary business rules. In this case, something like:
.net 中的验证检查属性。假设您有两个字符串属性,field1 和 field2。只需添加一个这样的属性即可。
详细信息请参见此处,以及 MinLength 等其他验证:https://stackoverflow.com/a/69621414/6742644
Validation in .net checks properties. Let's say you have two string properties, field1 and field2. Just add a property like this.
Details here, with additional validations like MinLength etc: https://stackoverflow.com/a/69621414/6742644
如果您想对任何 .Net 类进行复杂的验证,而不用注释来对它们进行修饰,请查看 FluentValidation,或者对于 .Net 2.0,FluentValidation for 2.0
If you want to do complex validation against any .Net class, without litering them with annotations, look at FluentValidation, or for .Net 2.0, FluentValidation for 2.0