gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:55:40 26 4
gpt4 key购买 nike

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

如果您想拥有 2 个组(或更多组):
[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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com