数据注释进行验证,至少需要一个领域? [英] Data Annotations for validation, at least one required field?

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

问题描述

如果我有一个搜索对象与字段列表,我可以使用System.ComponentModel.DataAnnotations命名空间,将其设置为验证在搜索领域中的至少一个不为空或空?即所有字段都是可选的,但至少每个人都应该进入。

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.

请注意,对于这个工作,你需要使用可为空类型,值类型将默认为 0

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天全站免登陆