ASP.NET MVC 3 数据注释:动态添加验证

发布于 2024-11-09 13:05:13 字数 1255 浏览 0 评论 0 原文

我是数据注释的新手。我想知道是否可以(以及如何)动态添加一些验证。解释原因非常广泛,但我有一个在创建时接收和对象的 ViewModel。在该对象中,我必须检查某些属性,并根据其值我应该进行或不进行一些验证。

一个例子:

public class ProfileViewModel
{
    [Required(ErrorMessage = "The field {0} is required")]
    [Display(Name = "Client Code")]
    public int ClientCode { get; set; }

    [Required(ErrorMessage = "The field {0} is required")]
    [StringLength(100, ErrorMessage = "The field {0} must have up to 100 characters.")]
    [Display(Name = "Company")]
    public string Company { get; set; }

    [StringLength(50, ErrorMessage = "The field {0} must have up to 50 characters.")]
    [Display(Name = "Name")]
    public string Name { get; set; }

    [StringLength(50, ErrorMessage = "The field {0} must have up to 50 characters.")]
    [Display(Name = "LastName")]
    public string LastName { get; set; }

    public ProfileViewModel(User usr)
    {
        if (usuario.ClientCode != null)
        {
            ClientCode = Convert.ToInt32(usr.ClientCode);
        }
        else
        {
             //ClientCode and Company are not yet required.
             //Name and LastName are now required.
        }
        Company = usr.Company;
        Name = usr.Name;
        LastName = usr.LastName;
    }
}

I'm new with data annotation. I'd like to know if it possible (and how) to add some validation dynamically. It is very extensive to explain why, but I've a ViewModel that receives and object when created. In that object I must check for some property and depending its value I should have or not some validations.

An example:

public class ProfileViewModel
{
    [Required(ErrorMessage = "The field {0} is required")]
    [Display(Name = "Client Code")]
    public int ClientCode { get; set; }

    [Required(ErrorMessage = "The field {0} is required")]
    [StringLength(100, ErrorMessage = "The field {0} must have up to 100 characters.")]
    [Display(Name = "Company")]
    public string Company { get; set; }

    [StringLength(50, ErrorMessage = "The field {0} must have up to 50 characters.")]
    [Display(Name = "Name")]
    public string Name { get; set; }

    [StringLength(50, ErrorMessage = "The field {0} must have up to 50 characters.")]
    [Display(Name = "LastName")]
    public string LastName { get; set; }

    public ProfileViewModel(User usr)
    {
        if (usuario.ClientCode != null)
        {
            ClientCode = Convert.ToInt32(usr.ClientCode);
        }
        else
        {
             //ClientCode and Company are not yet required.
             //Name and LastName are now required.
        }
        Company = usr.Company;
        Name = usr.Name;
        LastName = usr.LastName;
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

妄司 2024-11-16 13:05:13

我认为做我想做的事情的最简单方法是实现 IValidatableObject

public class Product : IValidatableObject
{
    public int Prop1 { get; set; }
    public int Prop2 { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (Prop1 < Prop2)
            yield return new ValidationResult("Property 1 can't be less than Property 2");
    }
}

另请参阅:类-使用 ASP.NET MVC 3 进行级别模型验证

I think that the simplest way of doing what I wanted is implementing IValidatableObject:

public class Product : IValidatableObject
{
    public int Prop1 { get; set; }
    public int Prop2 { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (Prop1 < Prop2)
            yield return new ValidationResult("Property 1 can't be less than Property 2");
    }
}

See also: Class-Level Model Validation with ... ASP.NET MVC 3

书信已泛黄 2024-11-16 13:05:13

自定义属性

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class CustomRequiredIfAttribute : CustomAttribute
{
    private RequiredAttribute innerAttribute = new RequiredAttribute();
    public string DependentProperty { get; set; }
    public object TargetValue { get; set; }

    public CustomRequiredIfAttribute()
    {
    }

    public CustomRequiredIfAttribute(string dependentProperty, object targetValue)
        : base()
    {
        this.DependentProperty = dependentProperty;
        this.TargetValue = targetValue;
    }

    public override bool IsValid(object value)
    {
        return innerAttribute.IsValid(value);
    }
}

自定义 RequiredIfValidator

using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace Custom.Web.Validation
{
    public class RequiredIfValidator : DataAnnotationsModelValidator<CustomRequiredIfAttribute>
    {
        public RequiredIfValidator(ModelMetadata metadata, ControllerContext context, CustomRequiredIfAttribute attribute)
            : base(metadata, context, attribute)
        {
        }

        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            return base.GetClientValidationRules();
        }

        public override IEnumerable<ModelValidationResult> Validate(object container)
        {
            // get a reference to the property this validation depends upon
            var field = Metadata.ContainerType.GetProperty(Attribute.DependentProperty);

            if (field != null)
            {
                // get the value of the dependent property
                object value = field.GetValue(container, null);

                // compare the value against the target value
                if (this.IsEqual(value) || (value == null && Attribute.TargetValue == null))
                {
                    // match => means we should try validating this field
                    if (!Attribute.IsValid(Metadata.Model))
                    {
                        // validation failed - return an error
                        yield return new ModelValidationResult { Message = ErrorMessage };
                    }
                }
            }
        }

        private bool IsEqual(object dependentPropertyValue)
        {
            bool isEqual = false;

            if (Attribute.TargetValue != null && Attribute.TargetValue.GetType().IsArray)
            {
                foreach (object o in (Array)Attribute.TargetValue)
                {
                    isEqual = o.Equals(dependentPropertyValue);
                    if (isEqual)
                    {
                        break;
                    }
                }
            }
            else
            {
                isEqual = Attribute.TargetValue.Equals(dependentPropertyValue);
            }

            return isEqual;
        }
    }
}

注册自定义 DataAnnotationsModelValidatorProvider

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomRequiredIfAttribute), typeof(RequiredIfValidator));

ViewModel 中使用此 CustomRequiredIf

[CustomRequiredIf("CategoryId", 3, ErrorMessageResourceName = GlobalResourceLiterals.AccountGroup_Required)]
public string AccountGroup { get; set; }

Custom Attribute:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class CustomRequiredIfAttribute : CustomAttribute
{
    private RequiredAttribute innerAttribute = new RequiredAttribute();
    public string DependentProperty { get; set; }
    public object TargetValue { get; set; }

    public CustomRequiredIfAttribute()
    {
    }

    public CustomRequiredIfAttribute(string dependentProperty, object targetValue)
        : base()
    {
        this.DependentProperty = dependentProperty;
        this.TargetValue = targetValue;
    }

    public override bool IsValid(object value)
    {
        return innerAttribute.IsValid(value);
    }
}

Custom RequiredIfValidator

using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace Custom.Web.Validation
{
    public class RequiredIfValidator : DataAnnotationsModelValidator<CustomRequiredIfAttribute>
    {
        public RequiredIfValidator(ModelMetadata metadata, ControllerContext context, CustomRequiredIfAttribute attribute)
            : base(metadata, context, attribute)
        {
        }

        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            return base.GetClientValidationRules();
        }

        public override IEnumerable<ModelValidationResult> Validate(object container)
        {
            // get a reference to the property this validation depends upon
            var field = Metadata.ContainerType.GetProperty(Attribute.DependentProperty);

            if (field != null)
            {
                // get the value of the dependent property
                object value = field.GetValue(container, null);

                // compare the value against the target value
                if (this.IsEqual(value) || (value == null && Attribute.TargetValue == null))
                {
                    // match => means we should try validating this field
                    if (!Attribute.IsValid(Metadata.Model))
                    {
                        // validation failed - return an error
                        yield return new ModelValidationResult { Message = ErrorMessage };
                    }
                }
            }
        }

        private bool IsEqual(object dependentPropertyValue)
        {
            bool isEqual = false;

            if (Attribute.TargetValue != null && Attribute.TargetValue.GetType().IsArray)
            {
                foreach (object o in (Array)Attribute.TargetValue)
                {
                    isEqual = o.Equals(dependentPropertyValue);
                    if (isEqual)
                    {
                        break;
                    }
                }
            }
            else
            {
                isEqual = Attribute.TargetValue.Equals(dependentPropertyValue);
            }

            return isEqual;
        }
    }
}

Register custom DataAnnotationsModelValidatorProvider

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomRequiredIfAttribute), typeof(RequiredIfValidator));

Use this CustomRequiredIf in the ViewModel

[CustomRequiredIf("CategoryId", 3, ErrorMessageResourceName = GlobalResourceLiterals.AccountGroup_Required)]
public string AccountGroup { get; set; }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文