88

I have the following viewmodel definition

public class AccessRequestViewModel
{
    public Request Request { get; private set; }
    public SelectList Buildings { get; private set; }
    public List<Person> Persons { get; private set; }
}

So in my application there must be at least 1 person for an access request. What approach might you use to validate? I don't want this validation to happen in my controller which would be simple to do. Is the only choice a custom validation attribute?

Edit: Currently performing this validation with FluentValidation (nice library!)

RuleFor(vm => vm.Persons)
                .Must((vm, person) => person.Count > 0)
                .WithMessage("At least one person is required");
Carrie Kendall
  • 11,124
  • 5
  • 61
  • 81
ryan
  • 6,541
  • 5
  • 43
  • 68

7 Answers7

189

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<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");
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • It looks like I need to use the overload Must() to use persons.Count, please see my edit and let me know if you have a version that is friendlier :) – ryan Mar 01 '11 at 13:45
  • 1
    @ryan, indeed there are two overloads of this method as [shown in the documentation](http://fluentvalidation.codeplex.com/wikipage?title=Validators&referringTitle=Documentation&ANCHOR#Predicate). So my version is friendlier. Don't worry if Visual Studio underlines it as error. It should work if you try to compile. It's just that VS Intellisense is not advanced enough to understand it :-) So `RuleFor(x => x.Persons).Must(x => x.Count > 0).WithMessage("At least a person is required");` will compile and work fine. – Darin Dimitrov Mar 01 '11 at 13:47
  • Strange, now it isn't underlining. Thanks! – ryan Mar 01 '11 at 14:11
  • Thank you Darin, you picked a cool attribute name (: Just curious if you are using any validation framework for *client-side* as well. Built-in *data annotations* provide the advantage of client side if one find useful. – Saro Taşciyan Oct 15 '14 at 14:06
  • How should I use it in razor? If i write @foreach(var p in Model.Person){...} @Html.ValidationMessageFor(model => Model.Person) validation server method is called but validation message is not shown. – Kate Aug 24 '16 at 11:10
  • Darin, is there any way to plumb this up with `IClientValidatable`? It's hard because we're never rendering an input control for `List Persons` specifically.... it's `EditorFor` usually just contains a collection of the individual models, so the `data-val-*` attributes don't have an `` specifically to attach to and subsequently get parsed by Unobtrusive Validation. – KyleMit Mar 30 '18 at 12:52
  • I would like normal validation to take place if one person is added to see if that person has a name populated. A normal [Required] on person.Name. The validation check does skip if List is null. Good start. But it's a real issue since model validation gets passed if a person is added without a name. I think the issue might be Blazor specific – ryan g Jun 06 '20 at 15:11
24

Following code works in asp.net core 1.1.

[Required, MinLength(1, ErrorMessage = "At least one item required in work order")]
public ICollection<WorkOrderItem> Items { get; set; }
rahulmohan
  • 1,285
  • 11
  • 19
  • 1
    It seems that this no longer works in .NET Core 2.1.0 (Preview 1) – Sven Apr 09 '18 at 11:56
  • 4
    This works in .Net Core 2.2, I have tried this on a List type. If you want a separate custom message for [Required] attribute that's possible too. [Required(ErrorMessage = "Missing Meters"), MinLength(1, ErrorMessage = "Atleast 1 meter is required")] public List Meters { get; set; } – Jeshwel May 25 '19 at 19:53
  • Nowadays, `MinLength` DataAnnotation is working fine. I tested it in .Net 5. Also, I think `Required` it is not necessary, since `MinLength` already implies it. I let you `MinLength` official documentation https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.minlengthattribute – cesAR Mar 03 '21 at 15:07
19

Another possible way to handle the count validations for view model object's collection members, is to have a calculated property returning the collection or list count. A RangeAttribute can then be applied like in the code below to enforce count validation:

[Range(minimum: 1, maximum: Int32.MaxValue, ErrorMessage = "At least one item needs to be selected")]
public int ItemCount
{
    get
    {
        return Items != null ? Items.Length : 0;
    }
}

In the code above, ItemCount is an example calculated property on a view model being validated, and Items is an example member collection property whose count is being checked. In this example, at least one item is enforced on the collection member and the maximum limit is the maximum value an integer can take, which is, for most of the practical purposes, unbounded. The error message on validation failure can also be set through the RangeAttribute's ErrorMessage member in the example above.

Sudhir
  • 421
  • 4
  • 7
10

Darin's answer is good but the version below will automatically give you a useful error message.

public class MinimumElementsAttribute : ValidationAttribute
{
    private readonly int minElements;

    public MinimumElementsAttribute(int minElements)
    {
        this.minElements = minElements;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var list = value as IList;

        var result = list?.Count >= minElements;

        return result
            ? ValidationResult.Success
            : new ValidationResult($"{validationContext.DisplayName} requires at least {minElements} element" + (minElements > 1 ? "s" : string.Empty));
    }
}

Usage:

[MinimumElements(1)]
public List<Customer> Customers {get;set}

[MinimumElements(2)]
public List<Address> Addresses {get;set}

Error message:

  • Customers requires at least 1 element
  • Addresses requires at least 2 elements
spottedmahn
  • 14,823
  • 13
  • 108
  • 178
Sam Shiles
  • 10,529
  • 9
  • 60
  • 72
2

You have two choices here, either create a Custom Validation Attribute and decorate the property with it, or you can make your ViewModel implement the IValidatableObject interface (which defines a Validate method)

Hope this helps :)

AbdouMoumen
  • 3,814
  • 1
  • 19
  • 28
0

One approach could be to use a private constructor and a static method to return an instance of the object.

public class AccessRequestViewModel
{
    private AccessRequesetViewModel() { };

    public static GetAccessRequestViewModel (List<Person> persons)
    {
            return new AccessRequestViewModel()
            {
                Persons = persons,
            };
    }

    public Request Request { get; private set; }
    public SelectList Buildings { get; private set; }
    public List<Person> Persons { get; private set; }
}

By always using the factory to instantiate your ViewModel, you can ensure that there will always be a person.

This probably isn't ideal for what you want, but it would likely work.

Ian P
  • 12,840
  • 6
  • 48
  • 70
0

It would be very clean and elegant to have a custom validation. Something like this:

public class AccessRequestViewModel
{
    public Request Request { get; private set; }
    public SelectList Buildings { get; private set; }
    [AtLeastOneItem]
    public List<Person> Persons { get; private set; }
}

Or [MinimumItems(1)].

goenning
  • 6,514
  • 1
  • 35
  • 42