我可以使用StringLengthAttribute以编程方式测试属性以检查它是否有效吗?

时间:2017-10-16 09:31:15

标签: c# data-annotations

鉴于我有:

[StringLength(10)]
public string Bibble {get; set;}

我可以单独检查Bibble是否有效吗?

我考虑过:

PropertyInfo[] props = typeof(MyBibbleObject).GetProperties();
foreach (PropertyInfo prop in props)
{
    object[] attrs = prop.GetCustomAttributes(true);
    foreach (object attr in attrs)
    {
        StringLengthAttribute stringLengthAttribute = attr as StringLengthAttribute;
        if (stringLengthAttribute != null)
        {
            string propName = prop.Name;

// Could be IsValid?
            stringLengthAttribute.IsValid()


        }
    }
}

但IsValid方法需要一个对象,我并不期待。我想知道是否有更好的方法来确定它是否有效。我必须按照每个房产来做。

1 个答案:

答案 0 :(得分:1)

您可以使用内置的Validator类。它的用法有点模糊,但仍然:

// instance is your MyBibbleObject object 
var ctx = new ValidationContext(instance);
// property to validate
ctx.MemberName = "Bibble";
// this will store results of validation. If empty - all fine
var results = new List<ValidationResult>();
// pass value to validate (it won't take it from your object)
Validator.TryValidateProperty(instance.Bibble, ctx, results);