作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如果我有一个包含字段列表的搜索对象,我是否可以使用 System.ComponentModel.DataAnnotations 命名空间将其设置为验证搜索中的至少一个字段不为空或不为空?即所有字段都是可选的,但至少应始终输入一个。
最佳答案
我已经扩展了 Zhaph 答案以支持属性分组。
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class AtLeastOnePropertyAttribute : ValidationAttribute
{
private string[] PropertyList { get; set; }
public AtLeastOnePropertyAttribute(params string[] propertyList)
{
this.PropertyList = propertyList;
}
//See http://stackoverflow.com/a/1365669
public override object TypeId
{
get
{
return this;
}
}
public override bool IsValid(object value)
{
PropertyInfo propertyInfo;
foreach (string propertyName in PropertyList)
{
propertyInfo = value.GetType().GetProperty(propertyName);
if (propertyInfo != null && propertyInfo.GetValue(value, null) != null)
{
return true;
}
}
return false;
}
}
[AtLeastOneProperty("StringProp", "Id", "BoolProp", 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; }
}
[AtLeastOneProperty("StringProp", "Id", ErrorMessage="You must supply at least one value")]
[AtLeastOneProperty("BoolProp", "BoolPropNew", 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; }
public bool? BoolPropNew { get; set; }
}
关于asp.net - 用于验证的数据注释,至少一个必填字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2712511/
我是一名优秀的程序员,十分优秀!