IDataErrorInfo - 是否存在集合不为空的验证属性?

发布于 2024-11-26 18:25:02 字数 87 浏览 8 评论 0原文

我不知道我是否找不到它或者它是否不存在,但是是否有任何验证属性可以检查集合是否为空/空?

如果没有,是否有关于如何创建我自己的验证属性的好资源?

I don't know if I just can't find it or if it does not exist, but is there any validation attribute which checks if a collection is null/empty or not?

If not, is there any good resource out there on how to create my own validation attribute?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

养猫人 2024-12-03 18:25:02

当您按照 default.kramer 建议使用 DataAnnotations 时,您可以创建将 Cu​​stomValidation 属性和 ValidationMethod 添加到集合属性和类中。请参阅下面的示例。

ValidationMethod 的重要部分是它是静态的,您必须将要验证的对象和 ValidationContext 添加到静态方法。

public class Order
{
[System.ComponentModel.DataAnnotations.Required( AllowEmptyStrings = false )]
public string Name
{
  get;
  set;
}

[System.ComponentModel.DataAnnotations.CustomValidation( typeof( Order ), "ValidateOrderLines" )]
public BindingList<OrderDetail> Lines
{
  get;
  set;
}

public static ValidationResult ValidateOrderLines( Order order, ValidationContext validationContext )
{
  ValidationResult result = new ValidationResult( "Lines are required!" );

  if ( order.Lines.Count != 0 )
    result = ValidationResult.Success;

  return result;
}

}

When you use DataAnnotations as per default.kramer suggested you can create add a CustomValidation attribute and ValidationMethod to you collection property and class. See example below.

The important part of the ValidationMethod is that it is Static and you have to add the object that you're validating and the ValidationContext to the static method.

public class Order
{
[System.ComponentModel.DataAnnotations.Required( AllowEmptyStrings = false )]
public string Name
{
  get;
  set;
}

[System.ComponentModel.DataAnnotations.CustomValidation( typeof( Order ), "ValidateOrderLines" )]
public BindingList<OrderDetail> Lines
{
  get;
  set;
}

public static ValidationResult ValidateOrderLines( Order order, ValidationContext validationContext )
{
  ValidationResult result = new ValidationResult( "Lines are required!" );

  if ( order.Lines.Count != 0 )
    result = ValidationResult.Success;

  return result;
}

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文