简体   繁体   English

使用IModelValidator创建自定义属性验证属性

[英]use IModelValidator to Create a Custom Property Validation Attribute

Below is a custom property validation from my textbook 以下是我的课本中的自定义属性验证

public class MustBeTrueAttribute : Attribute, IModelValidator
{
    public bool IsRequired => true;

    public string ErrorMessage { get; set; }

    public IEnumerable<ModelValidationResult> Validate(ModelValidationContext context)
    {
        bool? value = context.Model as bool?;
        if (!value.HasValue || value.Value == false)
        {
            return new List<ModelValidationResult> {
                    new ModelValidationResult("", ErrorMessage) // why first argument has to be empty?
                };
        }
        else
        {
            return Enumerable.Empty<ModelValidationResult>();
        }
    }
}

public class Appointment
{  
    public DateTime Date { get; set; }

    [MustBeTrue(ErrorMessage = "You must accept the terms")]
    public bool TermsAccepted { get; set; }
}

I have two questions: 我有两个问题:

Q1- IModelValidator interface doesn't define the IsRequired property, where it comes from and how this property is going to be used? Q1- IModelValidator接口没有定义IsRequired属性,它来自何处以及如何使用此属性?

Q2- why the first argument(memberName) in the ModelValidationResult 's constructor has to be empty "", under what circumstances we need to specify a value Q2-为什么在ModelValidationResult的构造函数中的第一个参数(成员名)必须为空“”,在什么情况下我们需要指定一个值

Q1: IModelValidator interface doesn't define the IsRequired property, where it comes from and how this property is going to be used? Q1: IModelValidator接口没有定义IsRequired属性,它来自何处以及如何使用此属性?

Ans: In this case, the property IsRequired is useless, because it isn't used in your code. 回答:在这种情况下,属性IsRequired是无用的,因为在您的代码中未使用它。

Q2: why the first argument(memberName) in the ModelValidationResult 's constructor has to be empty "", under what circumstances we need to specify a value Q2:为什么在ModelValidationResult的构造函数中的第一个参数(成员名)必须为空“”,在什么情况下我们需要指定一个值

Ans: Actually, it doesn't have to be empty. 回答:实际上,它不必为空。 It depends on what level you'd like to validate. 这取决于您要验证的级别。 Once you registered your custom validator, you might call it in your Controller to validate your model. 注册自定义验证器后,您可以在Controller中调用它以验证模型。 So if this validator is only for one model, you can validate all the properties with a Switch ... Case statement and give those properties a specific name. 因此,如果此验证器仅用于一个模型,则可以使用Switch ... Case语句验证所有属性,并为这些属性指定特定的名称。 On the other hand, if this validator will be used to validate many different models. 另一方面,如果此验证器将用于验证许多不同的模型。 You may need to consider whether it is suitable to specify a value. 您可能需要考虑是否适合指定值。

public IEnumerable<ModelValidationResult> Validate(ModelValidationContext context)
{
    if (context != null)
    {
        switch (context.ModelMetadata.PropertyName)
        {
            case "TermsAccepted":
                if (!context.Model.TermsAccepted) {
                    return new ModelValidationResult[]
                    {
                        new ModelValidationResult 
                        {
                            MemberName = "TermsAccepted",
                            Message = "You must accept the terms"
                        }
                    };
                }
                break; 
            default:
        }
        return new List<ModelValidationResult> 
        {
            new ModelValidationResult("", ErrorMessage)
        };
    }

    return Enumerable.Empty<ModelValidationResult>();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM