如何使用 IValidatableObject? [英] How do I use IValidatableObject?

查看:65
本文介绍了如何使用 IValidatableObject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解 IValidatableObject 用于验证对象的方式,让一个对象可以相互比较属性.

I understand that IValidatableObject is used to validate an object in a way that lets one compare properties against each other.

我仍然希望使用属性来验证单个属性,但我想在某些情况下忽略某些属性的失败.

I'd still like to have attributes to validate individual properties, but I want to ignore failures on some properties in certain cases.

在下面的情况下,我是否试图错误地使用它?如果不是,我该如何实现?

Am I trying to use it incorrectly in the case below? If not how do I implement this?

public class ValidateMe : IValidatableObject
{
    [Required]
    public bool Enable { get; set; }

    [Range(1, 5)]
    public int Prop1 { get; set; }

    [Range(1, 5)]
    public int Prop2 { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (!this.Enable)
        {
            /* Return valid result here.
             * I don't care if Prop1 and Prop2 are out of range
             * if the whole object is not "enabled"
             */
        }
        else
        {
            /* Check if Prop1 and Prop2 meet their range requirements here
             * and return accordingly.
             */ 
        }
    }
}

推荐答案

首先,感谢@paper1337 为我指出正确的资源......我没有注册所以我不能投票给他,请做所以如果其他人读到这个.

First off, thanks to @paper1337 for pointing me to the right resources...I'm not registered so I can't vote him up, please do so if anybody else reads this.

这是如何完成我想要做的事情.

Here's how to accomplish what I was trying to do.

可验证类:

public class ValidateMe : IValidatableObject
{
    [Required]
    public bool Enable { get; set; }

    [Range(1, 5)]
    public int Prop1 { get; set; }

    [Range(1, 5)]
    public int Prop2 { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var results = new List<ValidationResult>();
        if (this.Enable)
        {
            Validator.TryValidateProperty(this.Prop1,
                new ValidationContext(this, null, null) { MemberName = "Prop1" },
                results);
            Validator.TryValidateProperty(this.Prop2,
                new ValidationContext(this, null, null) { MemberName = "Prop2" },
                results);

            // some other random test
            if (this.Prop1 > this.Prop2)
            {
                results.Add(new ValidationResult("Prop1 must be larger than Prop2"));
            }
        }
        return results;
    }
}

如果验证失败,

使用 Validator.TryValidateProperty() 将添加到结果集合中.如果没有失败的验证,则不会向结果集合添加任何内容,这表明成功.

Using Validator.TryValidateProperty() will add to the results collection if there are failed validations. If there is not a failed validation then nothing will be add to the result collection which is an indication of success.

进行验证:

    public void DoValidation()
    {
        var toValidate = new ValidateMe()
        {
            Enable = true,
            Prop1 = 1,
            Prop2 = 2
        };

        bool validateAllProperties = false;

        var results = new List<ValidationResult>();

        bool isValid = Validator.TryValidateObject(
            toValidate,
            new ValidationContext(toValidate, null, null),
            results,
            validateAllProperties);
    }

重要的是将 validateAllProperties 设置为 false 以使此方法工作.当 validateAllProperties 为 false 时,仅检查具有 [Required] 属性的属性.这允许 IValidatableObject.Validate() 方法处理条件验证.

It is important to set validateAllProperties to false for this method to work. When validateAllProperties is false only properties with a [Required] attribute are checked. This allows the IValidatableObject.Validate() method handle the conditional validations.

这篇关于如何使用 IValidatableObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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