0

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.

1
  • 1
    You're boxing value types then comparing them.. Commented Jan 24, 2013 at 5:33

1 Answer 1

1

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;
        }
Sign up to request clarification or add additional context in comments.

1 Comment

stores the array of values in it so Values[0] = int[3] -> happen when they are different from type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.