How to return a property name when comparing two properties at class-level
Posted
by CodeMonkey
on Stack Overflow
See other posts from Stack Overflow
or by CodeMonkey
Published on 2010-05-24T20:05:43Z
Indexed on
2010/05/25
17:31 UTC
Read the original article
Hit count: 254
Hi
I have implemented an 'EqualTo' Validation Attribute, that compares two Properties of an object, during ModelBinding in ASP.NET MVC 2.
The problem I have is not with it not working, because it does work.
The problem is, when I do my request - which is an ajax request - I get back errors to my front-end, where it sets a class on the input fields to indicate invalid input. What it does is iterate through a list of Errors (in a JsonResult), and set a class.
This is all dandy.
But the ValidationAtrribute I am having trouble with is set at a Class-level, i.e., it's not like other ValidationAttributes where you set something like "[Required]" or something like that.
[AttributeUsage(AttributeTargets.Class, AllowMultiple=true, Inherited=false)]
public class EqualToAttribute : ValidationAttribute
{
public String SourceProperty { get; set; }
public String MatchProperty { get; set; }
public EqualToAttribute(string source, string match)
{
SourceProperty = source;
MatchProperty = match;
}
public override Boolean IsValid(Object value)
{
Type objectType = value.GetType();
PropertyInfo[] properties = objectType.GetProperties();
object sourceValue = new object();
object matchValue = new object();
Type sourceType = null;
Type matchType = null;
int counter = 0;
foreach (PropertyInfo propertyInfo in properties)
{
if (propertyInfo.Name == SourceProperty || propertyInfo.Name == MatchProperty)
{
if (counter == 0)
{
sourceValue = propertyInfo.GetValue(value, null);
sourceType = propertyInfo.GetValue(value, null).GetType();
}
if (counter == 1)
{
matchValue = propertyInfo.GetValue(value, null);
matchType = propertyInfo.GetValue(value, null).GetType();
}
counter++;
if (counter == 2)
{
break;
}
}
}
if (sourceType != null && matchType != null)
{
return sourceValue.ToString().Equals(matchValue.ToString());
//return Convert.ChangeType(sourceValue, sourceType) == Convert.ChangeType(matchValue, matchType);
}
return false;
}
private object _typeId = new object();
public override object TypeId
{
get
{
return this._typeId;
}
}
}
Now this code works, except for the fact that the validation process does not return which Property failed. And I simply can't figure out how to make it return one of the two. In reality I don't care which one it returns.. because both are failing..
Do you have an idea how to make it return the/or both Property/Properties that is/are failing.
© Stack Overflow or respective owner