Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 387
franklores Avatar asked Mar 14 '14 16:03

franklores


2 Answers

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; }
}
like image 169
Neil Smith Avatar answered Sep 20 '22 20:09

Neil Smith


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).

like image 20
Andrei Avatar answered Sep 20 '22 20:09

Andrei