Reputation: 10330
I'm writing a MVC custom validation. It will be valid for list of specific values. Example:
[Values(30, 60, 120)]
public int SelectTop { get; set; }
But It doesn't work with my validation. This is codes:
public class ValuesAttribute : ValidationAttribute
{
public object[] Values { get; private set; }
public Type Type { get; private set; }
public ValuesAttribute(params int[] values)
: this(typeof(int), values)
{
}
public ValuesAttribute(params double[] values)
: this(typeof(double), values)
{
}
public ValuesAttribute(Type type, params object[] values)
{
this.Type = type;
this.Values = values;
}
public override bool IsValid(object value)
{
foreach (var v in this.Values)
{
if (object.Equals(v, value))
{
return true;
}
}
return false;
}
}
Please help me to find the problem. Thanks.
Upvotes: 0
Views: 477
Reputation: 7443
This line
public object[] Values { get; private set; }
stores the array of values in it so Values[0] = int[3]
Change your code to:
public override bool IsValid(object value) {
int[] valueSet = this.Values[0] as int[];
if (valueSet == null) {
throw new Exception("Values must be provided");
}
foreach (var v in valueSet) {
if (object.Equals(v, value)) {
return true;
}
}
return false;
}
Upvotes: 1