如果我有一个带有字段列表的搜索对象,是否可以使用System.ComponentModel.DataAnnotation命名空间将其设置为验证搜索中至少有一个字段不为Null或空?也就是说,所有字段都是可选的,但至少应该始终输入一个字段.
如果我有一个带有字段列表的搜索对象,是否可以使用System.ComponentModel.DataAnnotation命名空间将其设置为验证搜索中至少有一个字段不为Null或空?也就是说,所有字段都是可选的,但至少应该始终输入一个字段.
我会为此创建一个自定义验证器——它不会提供客户端验证,只提供服务器端验证.
请注意,要使其工作,您需要使用nullable
种类型,因为值类型默认为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中.
请注意,您可以扩展它来判断返回的属性的类型,或者如果愿意,可以查找它们上的属性以包括/排除验证——这是假设一个通用验证器不知道它正在验证的类型.