自定义验证属性



目前我尝试通过同一类的另一个属性来验证一个属性。我收到一个错误,告诉我以下内容:

非静态字段、方法或属性需要对象引用

对于以下代码片段,这种错误对我来说绝对有意义。但无论如何,我尝试验证属性 A(在我的示例中 OrderNumber(以验证属性 B 的值(在我的示例 Level 中(。

是否有可能通过使用验证注释来做到这一点?

这是我目前的代码:

public class A
{
/// <summary>
/// Level 
/// </summary>
public string Level { get; set; }
public B B {get;set;}
}
public class B
{
/// <summary>
/// Order Number
/// </summary>
[Level(A.Level)]
public int? OrderNumber { get; set; }
}

public class LevelAttribute : ValidationAttribute
{
private string Dlevel { get; set; }
public LevelAttribute(string dlevel)
{
this.Dlevel = dlevel;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value!=null && (Dlevel.Equals("D1")||Dlevel.Equals("D2")))
{
return new ValidationResult("Invalid Error Message");
}
return ValidationResult.Success;
}
}

感谢您的帮助。

在自定义特性构造函数中无法直接引用实例成员(方法、属性、字段(。但是有一种间接的方法,通过定义属性名称并通过反射解析相应的属性值:

public class A
{
public A()
{
Level = "D3";
}
public string Level { get; set; }
public B B { get; set; }
}
public class B
{
[Level("MyNamespace.A.Level")]
public int? OrderNumber { get; set; }
}
public class LevelAttribute : ValidationAttribute
{
private string PropName { get; set; }
public LevelAttribute(string prop)
{
this.PropName = prop;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
System.Reflection.PropertyInfo property = null;
object objectinstance = null;
if (this.PropName.Contains("."))
{
string classname = PropName.Substring(0, PropName.LastIndexOf("."));
string prop = PropName.Substring(PropName.LastIndexOf(".") + 1);
Type type = Type.GetType(classname);
objectinstance = System.Activator.CreateInstance(type);
property = type.GetProperty(prop, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
}
else
{
objectinstance = validationContext.ObjectInstance;
property = validationContext.ObjectInstance.GetType().GetProperty(this.PropName, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
}
object propertyvalue = property.GetValue(objectinstance, new object[0]);
if (value != null && propertyvalue != null && (propertyvalue.Equals("D1") || propertyvalue.Equals("D2")))
{
return new ValidationResult("Invalid Error Message");
}
return ValidationResult.Success;
}
}

最新更新