数组必须包含1个元素

时间:2012-11-13 13:25:19

标签: c# .net asp.net-mvc asp.net-mvc-3 model-validation

我有以下课程:

public class CreateJob
{
    [Required]
    public int JobTypeId { get; set; }
    public string RequestedBy { get; set; }
    public JobTask[] TaskDescriptions { get; set; }
}

我想在TaskDescriptions之上有一个数据注释,以便数组必须包含至少一个元素?很像[Required]。这可能吗?

8 个答案:

答案 0 :(得分:44)

可以使用标准MinLengthAttribute验证属性来完成,但仅适用于数组:

public class CreateJob
{
    [Required]
    public int JobTypeId { get; set; }
    public string RequestedBy { get; set; }
    [MinLength(1)]
    public JobTask[] TaskDescriptions { get; set; }
}

答案 1 :(得分:21)

之前我见过一个自定义验证属性,如下所示:

(我已经给出了带有列表的示例但可以适用于数组,或者您可以使用列表)

public class MustHaveOneElementAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var list = value as IList;
        if (list != null)
        {
            return list.Count > 0;
        }
        return false;
    }
}
[MustHaveOneElementAttribute (ErrorMessage = "At least a task is required")]
public List<Person> TaskDescriptions { get; private set; }

答案 2 :(得分:2)

这是@dove解决方案的一个改进版本,它处理不同类型的集合,如HashSet,List等......

public class MustHaveOneElementAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var collection = value as IEnumerable;
        if (collection != null && collection.GetEnumerator().MoveNext())
        {
            return true;
        }
        return false;
    }
}

答案 3 :(得分:1)

请允许我提供有关在.NET Core中使用MinLengthAttribute的附注。

Microsoft建议使用从.NET Core 2.0开始的Razor Pages。

目前,使用MinLengthAttribute对PageModel中的属性进行验证不起作用:

    if (body.asStar() != null) {
        // body is a star
        body.asStar().shineBrightly();
    }

当SelectedStores.Count()== 0时,ModelState.IsValid返回true。

使用.NET Core 2.1 Preview 2进行测试。

答案 4 :(得分:1)

刚刚更新 Dove (@dove) 对 C# 9 语法的响应:

    public class MustHaveOneElementAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
            => value is IList {Count: > 0};
    }

答案 5 :(得分:0)

如果值为null,则MinLength属性将该值视为有效。因此,只需将模型中的属性初始化为空数组即可。

MinLength(1, ErrorMessageResourceName = nameof(ValidationErrors.AtLeastOneSelected), ErrorMessageResourceType = typeof(ValidationErrors))]
int[] SelectedLanguages { get; set; } = new int[0];

答案 6 :(得分:0)

对于mynkow的答案,我添加了将最小计数值传递给属性并生成有意义的失败消息的功能:

public class MinimumElementsRequiredAttribute : ValidationAttribute
{
  private readonly int _requiredElements;

  public MinimumElementsRequiredAttribute(int requiredElements)
  {
    if (requiredElements < 1)
    {
      throw new ArgumentOutOfRangeException(nameof(requiredElements), "Minimum element count of 1 is required.");
    }

    _requiredElements = requiredElements;
  }

  protected override ValidationResult IsValid(object value, ValidationContext validationContext)
  {
    if (!(value is IEnumerable enumerable))
    {
      return new ValidationResult($"The {validationContext.DisplayName} field is required.");
    }

    int elementCount = 0;
    IEnumerator enumerator = enumerable.GetEnumerator();
    while (enumerator.MoveNext())
    {
      if (enumerator.Current != null && ++elementCount >= _requiredElements)
      {
        return ValidationResult.Success;
      }
    }

    return new ValidationResult($"At least {_requiredElements} elements are required for the {validationContext.DisplayName} field.");
  }
}

像这样使用它:

public class Dto
{
  [MinimumElementsRequired(2)]
  public IEnumerable<string> Values { get; set; }
}

答案 7 :(得分:0)

您必须使用2个标准注释属性

public class CreateJob
{
    [MaxLength(1), MinLength(1)]
    public JobTask[] TaskDescriptions { get; set; }
}
相关问题