0

I use C# MVC, I have a list:

 public List<int?> SomeList { get; set; }  

and when the user try to enter a letter instead of a number, it shows a validation error because the list's type is INT.

I want to add more validation, like "range" (not only) for the list's items (all of them will have the same attributes).

Can I do that? How?

TamarG
  • 3,522
  • 12
  • 44
  • 74
  • The answer is in your title - with what exactly do you have a problem? – flq Apr 24 '12 at 12:35
  • if I put [range(0,4)] before the list, it doesn't work.. I need that it will be for the items in the list, not for the list itself.. – TamarG Apr 24 '12 at 12:36

3 Answers3

0

You might want to look into the source of the rangeattribute, and create your own attribute (http://msdn.microsoft.com/en-us/library/cc668224.aspx) that will validate a generic list with a range.

There ya go.

SynerCoder
  • 12,493
  • 4
  • 47
  • 78
  • How does it help me for a list? – TamarG Apr 24 '12 at 12:40
  • 1
    I did it! :) I used that - http://stackoverflow.com/questions/9071351/how-to-get-model-validation-to-pickup-attributes-set-on-objects-in-a-list-in-mvc I created a new class that contains only an int field, and it has its own validation attributes, and then created a list of this class. – TamarG Apr 24 '12 at 12:53
0

You can always implement the validation yourself, especially if you want to implement arbitrary validation on various criteria

bool validate(int value){
    if ((value < min) || (value > max))
        return false;
}
msam
  • 4,259
  • 3
  • 19
  • 32
0

You'll have to create your own class that inherits from List<T>, then you can "hide" the Add method by declaring a new method:

    class TestList : List<int>
{
    public int MinValue { get; set; }
    public int MaxValue { get; set; }

    public TestList(int minValue, int maxValue)
    {
        this.MinValue = minValue;
        this.MaxValue = maxValue;
    }

    public new void Add(int item)
    {
        if (item < MinValue || item > MaxValue)
            throw new ArgumentException("Value is outside the acceptable range");

        base.Add(item);
    }
}

Edit: forgot to throw in the constructor.

mgnoonan
  • 7,060
  • 5
  • 24
  • 27