使用IValidatableObject验证时获取成员属性 [英] Get member attribute when validating using IValidatableObject

查看:79
本文介绍了使用IValidatableObject验证时获取成员属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用IValidatableObject验证在下列情况下一个复杂的对象。

I'm using IValidatableObject to validate a complex object in the following scenario.

public class Foo {
    [Required]
    public Bar Foobar { get; set; }
}

public class Bar : IValidatableObject {
    public int Id { get; set; }
    public string Name { get; set; }
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)  {
        // check if the current property instance is decorated with the Required attribute
        if(TheAboveConditionIsTrue) {
            // make sure the Name property is not null or empty
        }
    }
}

我不知道这是否是做到这一点的最好办法,如果不是我很高兴承担解决验证等方式的意见。

I don't know if this is the best way to do this, if not I'm happy to take comments on other ways of solving the validation.

推荐答案

创建的抽象基类,它实现 IValidatableObject ,并使其验证()虚拟方法:

Create an abstract base class for Foo that implements IValidatableObject and make its Validate() method virtual:

public abstract class FooBase : IValidatableObject
{
    public string OtherProperty { get; set; }

    public Bar Foobar { get; set; }
    public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var results = new List<ValidationResult>();

        //Validate other properties here or return null
        if (String.IsNullOrEmpty(OtherProperty))
            results.Add(new ValidationResult("OtherProperty is required", new[] { "OtherProperty" }));

        return results;
    }
}

现在实现你的基类或者 FooRequired FooNotRequired

Now implement your base class as either FooRequired or FooNotRequired:

public class FooRequired : FooBase
{
    public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var result = base.Validate(validationContext).ToList();
        result.AddRange(Foobar.Validate(validationContext));
        return result;
    }
}

public class FooNotRequired : FooBase
{
    //No need to override the base validate method.
}

酒吧类仍然会是这个样子:

Your Bar class would still look something like this:

public class Bar : IValidatableObject
{
    public int Id { get; set; }
    public string Name { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var results = new List<ValidationResult>();

        if (String.IsNullOrEmpty(Name))
            results.Add(new ValidationResult("Name is required", new[] { "Name" }));

        return results;
    }
}

用法:

FooBase foo1 = new FooRequired();
foo1.Validate(...);

FooBase foo2 = new FooNotRequired();
foo2.Validate(...);

这篇关于使用IValidatableObject验证时获取成员属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆