How to authenticate directly from the <T> list?

I have a model class:

public class MyModel() { //properties here... }

And I want to check the list of objects MyModel. So I created this validator:

class MyModelListValidator : AbstractValidator<List<MyModel>>
{
    public MyModelListValidator ()
    {
        RuleFor(x => x)
            .SetCollectionValidator(new MyModelValidator())
            .When(x => x != null);
    }

    private class MyModelValidator : AbstractValidator<MyModel>
    {
        public MyModelValidator()
        {
            //MyModel property validation here...
        }
    }
}

But the above does not work. An alternative is to create a class like:

public class MyModelList()
{
    public List<MyModel> Items { get; set; }
}

It will work.

But is there a way to do this without using this extra class?

+4
source share
1 answer

If you use data annotations to perform validation, you may 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<Person> 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<Person> 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");
0
source

Source: https://habr.com/ru/post/1653415/


All Articles