Lando
Lando

Reputation: 2348

How can I validate a List/Array Count in an MVC Model using Data Annotations?

How would one go about validating a nested List of Objects in an MVC Model?

I have an "Item" object which has an attached List of Revenue Entries:

public class ItemModel
{
    public int ItemID { get; set; }

    public virtual List<RevenueEntryModel> Revenues { get; set;}
}

This list can be edited on the page dynamically, and each item is validated individually using it's own model - "RevenueEntryModel". However, I want to be able to restrict users from entering Items without any Revenues.

Is it possible to validate whether this Revenues list is empty using Data Annotations? I'm already using Foolproof but I'm pretty sure it doesn't include this functionality.

Upvotes: 2

Views: 10169

Answers (2)

Deadlykipper
Deadlykipper

Reputation: 878

There's a previous answer that will help you here. It's a thorough answer, but basically you need to use custom validation attributes:

Upvotes: 1

souplex
souplex

Reputation: 981

You can apply your own logic that checks the number of items in the Revenues collection.

Apply a class level validation attribute to the ItemModel class. You could use System.ComponentModel.DataAnnotations.CustomValidationAttribute for this.

This points to a custom method you would create.

The attribute construct would look something like this:

[CustomValidation(typeof (MyClassWhereMethodIsLocated), "MyStaticMethodName")]

Checkout this blog for additional details

Upvotes: 0

Related Questions