asp.net – 用于验证的数据注释,至少一个必填字段?

如果我有一个包含字段列表的搜索对象,可以使用System.ComponentModel.DataAnnotations命名空间进行设置,以验证搜索中至少有一个字段不为空或为空吗?即所有的字段都是可选的,但至少应该输入一个字段。

解决方法

我会为此创建自定义验证器 – 它不会给客户端验证,只是服务器端。

请注意,为了使其工作,您需要使用可空类型,因为值类型将认为0或false:

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

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;
  }
}

然后,您可以使用以下方式装饰您的模型:

[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。

请注意,您可以扩展它以检查返回的属性类型,或者查找属性,以便包含/排除验证,如果你想 – 这是假设一个通用的验证器,不知道任何关于它验证的类型。

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....