How to add validation for a list in a ViewModel

787 views Asked by At

I have the following ViewModel:

public class InvitationViewModel
{
    public int id { get; set; }
    public string InvitationName { get; set; }
    public string Type { get; set; }
    public string RSVPStat { get; set; }
    public virtual List<Guests> guests { get; set; }
}

I want to add some validation for the List of Guests, is it possible to use data annotations for this or is there some other way?

Thanks for any suggestions.

2

There are 2 answers

2
Chris Pratt On

Since your question is a little unclear, I'll round the bases. You can add some validation to the list itself, if that's what you're looking for. That pretty much just includes Required, which would validate that the list has at least one item:

[Required]
public List<Guests> Guests { get; set; }

The keyword virtual allows a property, method or field to be overridden by a subclass. Most likely, you saw this on your entity and figured you need the same here in your view model. The reason entities use virtual on reference and navigation properties is that Entity Framework creates proxy classes of your entities in order to provide lazy-loading functionality. The proxies (which are just subclasses) override the reference and navigation properties to insert the lazy-loading code necessary.

If you're talking about adding validation attributes to the properties of the actual Guest class, you cannot do that just for the sake of a view model. Any validation you add to Guest will be for any use of Guest. There's nothing stopping you from also implementing a GuestViewModel or similar class, though, which you could then add whatever validation you like to.

2
gabnaim On

Do you want to validate each guest? In that case mark Guest up with Data annotations. If you want a validation on the list itself (i.e. number of guests), you can write you own ValidationAttribute, or you can implement IValidateableObject on your model.

Edit: if your view model requires different validation, create a GuestViewModel and mark it up with the required validation.