将变量数据传递给ValidationAttribute

时间:2016-08-16 19:01:34

标签: entity-framework data-annotations validationattribute

我要求在更改密码功能中将不同的最小长度值应用于基于用户角色创建的新密码。如果用户没有管理角色,则min length为12,如果他们具有admin角色,则min length为16。

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

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

验证属性设置如下:

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

我希望能够根据IsAdmin的值将MinLength的值设置为12或16但是我无法弄清楚如何装饰属性[PasswordMinLength(IsAdmin = myvarable )]。只允许常量。如何将一个属性值注入ValidationAttribute,我可以评估它以确定正确的最小长度?

谢谢!

1 个答案:

答案 0 :(得分:0)

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

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

}

我只是将一个IsAdmin属性添加到我的Model类中并装饰了PasswordMinLength属性,如下所示:

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

像魅力一样工作。谢谢史蒂夫!

相关问题