franklores
franklores

Reputation: 375

How to validate number of items in a list in mvc model

I am writing an online assessment form. On this form the user has to select a minimum of 3 and a maximum of 7 people who will provide an assessment on them. I have a form where the user adds the assessors and I display the list underneath this form. Once the user has finished adding assessors then click on the self assessment button to fill his/hers own self assessment.

What I want to do is to validate that indeed the number of assessors is in the right range before the user leaves the page.

The model is like this

public class AssessorsViewModel
{
    List<Assessor> Assessors { get; set; }
}

public class Assessor
{
    string Email { get; set; }
    string Name { get; set; }
}

I have validation attributes for the Assessor class so everytime the user adds an assessor I can validate this, but I can't figure out how to validate the Count on the Assessors List.

I am using ASP.net MVC.

Thanks in advance

Upvotes: 5

Views: 8714

Answers (3)

Nanz
Nanz

Reputation: 179

You could always add a custom validation attribute that would get fired when the model is validated.

Check the answer here on another question: ASP.NET MVC: Custom Validation by DataAnnotation

Upvotes: 2

Neil Smith
Neil Smith

Reputation: 2565

A custom ValidationAttribute would do it for you:

public class LimitCountAttribute : ValidationAttribute
{
    private readonly int _min;
    private readonly int _max;

    public LimitCountAttribute(int min, int max) {
        _min = min;
        _max = max;
    }

    public override bool IsValid(object value) {
        var list = value as IList;
        if (list == null)
            return false;

        if (list.Count < _min || list.Count > _max)
            return false;

        return true;
    }
}

Usage:

public class AssessorsViewModel
{
    [LimitCount(3, 7, ErrorMessage = "whatever"]
    List<Assessor> Assessors { get; set; }
}

Upvotes: 18

Andrei
Andrei

Reputation: 56716

You can simply validate this in the controller:

public ActionResult TheAction(AssessorsViewModel model)
{
    if (model.Assessors == null
        || model.Assessors.Count < 3
        || model.Assessors.Count > 7)
    {
        ModelState.AddModelError("Assessors", "Please enter note less than 3 and not more than 7 assessors.");
        return View(model);
    }
    ...
}

Another option would be to write a custom validation attribute. Here is an example of how to do this (the validator there is different, but the approach is clear).

Upvotes: 2

Related Questions