簡體   English   中英

使用IValidatableObject進行驗證時獲取成員屬性

[英]Get member attribute when validating using IValidatableObject

在以下情況下,我使用IValidatableObject來驗證復雜對象。

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
        }
    }
}

我不知道這是否是最好的方法,否則我很樂意就解決驗證的其他方法發表評論。

Foo創建一個實現IValidatableObject的抽象基類,並將其Validate()方法虛擬化:

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;
    }
}

現在將您的基類實現為FooRequiredFooNotRequired

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.
}

您的Bar類仍然看起來像這樣:

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(...);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM