ViewModel validation for a List

前端 未结 7 1642
梦谈多话
梦谈多话 2020-11-28 02:54

I have the following viewmodel definition

public class AccessRequestViewModel
{
    public Request Request { get; private set; }
    public SelectList Buildi         


        
7条回答
  •  佛祖请我去吃肉
    2020-11-28 03:03

    If you are using Data Annotations to perform validation you might need a custom attribute:

    public class EnsureOneElementAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            var list = value as IList;
            if (list != null)
            {
                return list.Count > 0;
            }
            return false;
        }
    }
    

    and then:

    [EnsureOneElement(ErrorMessage = "At least a person is required")]
    public List Persons { get; private set; }
    

    or to make it more generic:

    public class EnsureMinimumElementsAttribute : ValidationAttribute
    {
        private readonly int _minElements;
        public EnsureMinimumElementsAttribute(int minElements)
        {
            _minElements = minElements;
        }
    
        public override bool IsValid(object value)
        {
            var list = value as IList;
            if (list != null)
            {
                return list.Count >= _minElements;
            }
            return false;
        }
    }
    

    and then:

    [EnsureMinimumElements(1, ErrorMessage = "At least a person is required")]
    public List Persons { get; private set; }
    

    Personally I use FluentValidation.NET instead of Data Annotations to perform validation because I prefer the imperative validation logic instead of the declarative. I think it is more powerful. So my validation rule would simply look like this:

    RuleFor(x => x.Persons)
        .Must(x => x.Count > 0)
        .WithMessage("At least a person is required");
    

提交回复
热议问题