首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将变量数据传递给ValidationAttribute

将变量数据传递给ValidationAttribute
EN

Stack Overflow用户
提问于 2016-08-16 19:01:34
回答 1查看 892关注 0票数 2

我需要将更改密码函数中不同的最小长度值应用于基于用户角色创建的新密码。如果用户没有管理角色,则最小长度为12,如果用户具有管理角色,则最小长度为16。

当前代码没有这样的可变需求逻辑。新密码属性的实现在称为ChangePasswordData的模型类中是这样的:

代码语言:javascript
复制
    ///summary>
    /// Gets and sets the new Password.
    /// </summary>
    [Display(Order = 3, Name = "NewPasswordLabel", ResourceType = typeof(UserResources))]
    [Required]
    [PasswordSpecialChar]
    [PasswordMinLower]
    [PasswordMinUpper]
    [PasswordMaxLength]
    [PasswordMinLength]
    [PasswordMinNumber]
    public string NewPassword { get; set; }

验证属性设置如下:

代码语言:javascript
复制
/// <summary>
/// Validates Password meets minimum length.
/// </summary>
public class PasswordMinLength : ValidationAttribute
{
    public int MinLength { get; set; }

    public bool IsAdmin { get; set; }

    public PasswordMinLength()
    {
        // Set this here so we override the default from the Framework
        this.ErrorMessage = ValidationErrorResources.ValidationErrorBadPasswordLength;

        //Set the default Min Length
        this.MinLength = 12;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null || !(value is string) || !UserRules.PasswordMinLengthRule(value.ToString(), this.MinLength))
        {
            return new ValidationResult(this.ErrorMessageString, new string[] { validationContext.MemberName });
        }

        return ValidationResult.Success;
    }
}

我希望能够根据MinLength的值将IsAdmin的值设置为12或16,但是我不知道如何装饰属性PasswordMinLength(IsAdmin=myvarable)。只允许常量。如何将属性值注入ValidationAttribute,以求出正确的最小长度?

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-17 18:35:19

感谢Steve提供了一个示例(http://odetocode.com/blogs/scott/archive/2011/02/21/custom-data-annotation-validator-part-i-server-code.aspx)的链接,我有了我的验证问题的答案。以下是更新的代码:

代码语言:javascript
复制
/// <summary>
/// Validates Password meets minimum length.
/// </summary>
public class PasswordMinLength : ValidationAttribute
{
    public int MinLength { get; set; }

    public PasswordMinLength(string IsAdminName)
    {
        // Set this here so we override the default from the Framework
        this.ErrorMessage = ValidationErrorResources.ValidationErrorBadPasswordLength;
        IsAdminPropertyName = IsAdminName;
        //Set the default Min Length
        this.MinLength = 12;
    }

    public string IsAdminPropertyName{ get; set; }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(ErrorMessageString, name, IsAdminPropertyName);
    }

    protected bool? GetIsAdmin(ValidationContext validationContext)
    {
        var retVal = false;
        var propertyInfo = validationContext
                              .ObjectType
                              .GetProperty(IsAdminPropertyName);
        if (propertyInfo != null)
        {
            var adminValue = propertyInfo.GetValue(
                validationContext.ObjectInstance, null);

            return adminValue as bool?;
        }
        return retVal;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (GetIsAdmin(validationContext) != null)
        {
            if (GetIsAdmin(validationContext) == true)
                this.MinLength = 16;
            else
                this.MinLength = 12;
        }
        else
            this.MinLength = 12;

        if (value == null || !(value is string) || !UserRules.PasswordMinLengthRule(value.ToString(), this.MinLength))
        {
            return new ValidationResult(this.ErrorMessageString, new string[] { validationContext.MemberName });
        }

        return ValidationResult.Success;
    }

}

我只是向我的Model类添加了一个IsAdmin属性,并将PasswordMinLength属性修饰如下:

代码语言:javascript
复制
[Display(Order = 3, Name = "NewPasswordLabel", ResourceType = typeof(UserResources))]
[Required]
[PasswordSpecialChar]
[PasswordMinLower]
[PasswordMinUpper]
[PasswordMaxLength]
[PasswordMinLength("IsAdmin")]
[PasswordMinNumber]
public string NewPassword { get; set; }

public bool IsAdmin { get; set; }

就像一种魅力。谢谢史蒂夫!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38982573

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档