Custom Model Validator for MVC
Posted
by scottrakes
on Stack Overflow
See other posts from Stack Overflow
or by scottrakes
Published on 2010-04-17T18:50:56Z
Indexed on
2010/04/17
18:53 UTC
Read the original article
Hit count: 335
I am trying to add a custom model validation at the property level but need to pass in two values. Below is my class definition and validation implementation. When it runs, the "value" in the IsValid method is always null. I can get this working at the class level but the property level is causing me issues. What am I missing?
Event Class:
public class Event
{
public int? EventID {get;set;}
[ValidPURL("EventID", "PURLValue")]
public string PURLValue { get; set; }
...
}
Validation Class
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
public sealed class ValidPURL : ValidationAttribute
{
private const string _defaultErrorMessage = "Web address already exist.";
private readonly object _typeId = new object();
public ValidPURL(int eventID, string purlValue)
: base(_defaultErrorMessage)
{
EventID = eventID;
PURLValue = purlValue;
}
public int EventID
{
get;
private set;
}
public string PURLValue
{
get;
private set;
}
public override object TypeId
{
get
{
return _typeId;
}
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
EventID, PURLValue);
}
public override bool IsValid(object value)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
object eventIDValue = properties.Find(EventID, true /* ignoreCase */).GetValue(value);
object purlValue = properties.Find(PURLValue, true /* ignoreCase */).GetValue(value);
[Some Validation Logic against the database]
return true; } }
Thank for the help!
© Stack Overflow or respective owner