用于验证的数据注释,至少有一个必填字段? [英] Data Annotations for validation, at least one required field?

查看:39
本文介绍了用于验证的数据注释,至少有一个必填字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个包含字段列表的搜索对象,是否可以使用 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.

推荐答案

我会为此创建一个自定义验证器 - 它不会为您提供客户端验证,只会提供服务器端验证.

I'd create a custom validator for this - it won't give you client side validation, just server side.

请注意,要使其正常工作,您需要使用 nullable 类型,因为值类型将默认为 0false:

Note that for this to work, you'll need to be using nullable types, as value types will default to 0 or false:

首先创建一个新的验证器:

First create a new validator:

using System.ComponentModel.DataAnnotations;
using System.Reflection;

// This is a class-level attribute, doesn't make sense at the property level
[AttributeUsage(AttributeTargets.Class)]
public class AtLeastOnePropertyAttribute : ValidationAttribute
{
  // Have to override IsValid
  public override bool IsValid(object value)
  {
    //  Need to use reflection to get properties of "value"...
    var typeInfo = value.GetType();

    var propertyInfo = typeInfo.GetProperties();

    foreach (var property in propertyInfo)
    {
      if (null != property.GetValue(value, null))
      {
        // We've found a property with a value
        return true;
      }
    }

    // All properties were null.
    return false;
  }
}

然后你可以用这个来装饰你的模型:

You can then decorate your models with this:

[AtLeastOneProperty(ErrorMessage="You must supply at least one value")]
public class SimpleTest
{
    public string StringProp { get; set; }
    public int? Id { get; set; }
    public bool? BoolProp { get; set; }
}

然后,当您调用 ModelState.IsValid 时,您的验证器将被调用,您的消息将被添加到您视图上的 ValidationSummary.

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.

这篇关于用于验证的数据注释,至少有一个必填字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆