2

사용자의 역할에 따라 생성되는 새 암호로 암호 변경 기능의 다른 길이 값을 적용해야한다는 요구 사항이 있습니다. 사용자에게 관리 역할이 없으면 최소 길이는 12입니다. 관리자 역할이있는 경우 최소 길이는 16입니다.ValidationAttribute에 변수 데이터 전달

현재 코드에는 이러한 가변 요구 사항 논리가 없습니다. 새 암호 속성의 구현 때문에 모델 클래스에서 호출 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; 
    } 
} 

내가에 MINLENGTH의 값을 설정할 수 있도록하려면 12 또는 16 IsAdmin의 값을 기반으로 그러나 나는 [PasswordMinLength (IsAdmin = myvarable)] 속성을 장식하는 방법을 알아낼 수 없습니다. 상수 만 허용됩니다. 올바른 최소 길이를 결정하기 위해 평가할 수있는 ValidationAttribute에 속성 값을 삽입하려면 어떻게해야합니까?

감사합니다.

+0

속성 값에 정적 상수 만 허용되기 때문에 달성하고자하는 것은 불가능하다고 생각합니다. – DevilSuichiro

+0

변수 값으로 특성을 꾸밀 수는 없지만 유효성 검사 컨텍스트 항목 컬렉션이나 다른 메서드에 값을 주입하는 방법이 있습니다. 그래서 IsValid 내부에서 문제가되는 사용자가 관리 역할을 갖고 있는지를 평가할 수 있습니다. ? – djcohen66

+1

하나의 옵션은 [클래스 수준 유효성 검사] (http://weblogs.asp.net/scottgu/class-level-model-validation-with-ef-code-first-and-asp-net-mvc-3)를 사용하는 것입니다.)보기 모델. 그렇지 않으면 [PasswordMinLength ("IsAdmin")]과 같은 주석을 만든 다음 이와 유사한 기술을 사용하여 유효성 검사에서 해당 속성에 액세스 할 수 있어야합니다. http : //odetocode.com/blogs/scott/archive/2011/ 02/21/custom-data-annotation-validator-part-i-server-code.aspx –

답변

0

예 (http://odetocode.com/blogs/scott/archive/2011/02/21/custom-data-annotation-validator-part-i-server-code.aspx)에 대한 링크를 제공 한 Steve Greene에게 감사의 말을 전합니다. 여기에 업데이트 된 코드는 다음과 같습니다

/// <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 속성을 추가하고 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; } 

작품. 스티브 감사합니다!