2010-06-28 4 views
2

ASP.NET MVC 2에서 일련의 필드를 포함하는 Linq to sql 클래스가 있습니다. 이제 다른 필드에 특정 (열거 형) 값이있을 때 필드 중 하나가 필요합니다. 예를 들어,다른 필드를 기반으로 한 유효성 검사?

나는 지금까지 내가 속성으로 열거를 취할 수있는 사용자 정의 유효성 검사 속성을 쓴 왔어요,하지만 난 말할 수 없다 : EnumValue = this.OtherField

내가 어떻게해야합니까?

+0

필자는 일종의 유효성 검사가 필드가 아닌 클래스에 적용되어야한다고 생각합니다. – Jay

답변

4

MVC2에는 DataAnnotation을 얻는 방법을 보여주는 "PropertiesMustMatchAttribute"샘플이 있으며 .NET 3.5 및 .NET 4.0에서 모두 작동해야합니다.

[PropertiesMustMatch("NewPassword", "ConfirmPassword", ErrorMessage = "The new password and confirmation password do not match.")] 
public class ChangePasswordModel 
{ 
    public string NewPassword { get; set; } 
    public string ConfirmPassword { get; set; } 
} 

때 "IsValid : 당신이 그 속성을 사용하는 경우

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] 
public sealed class PropertiesMustMatchAttribute : ValidationAttribute 
{ 
    private const string _defaultErrorMessage = "'{0}' and '{1}' do not match."; 

    private readonly object _typeId = new object(); 

    public PropertiesMustMatchAttribute(string originalProperty, string confirmProperty) 
     : base(_defaultErrorMessage) 
    { 
     OriginalProperty = originalProperty; 
     ConfirmProperty = confirmProperty; 
    } 

    public string ConfirmProperty 
    { 
     get; 
     private set; 
    } 

    public string OriginalProperty 
    { 
     get; 
     private set; 
    } 

    public override object TypeId 
    { 
     get 
     { 
      return _typeId; 
     } 
    } 

    public override string FormatErrorMessage(string name) 
    { 
     return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, 
      OriginalProperty, ConfirmProperty); 
    } 

    public override bool IsValid(object value) 
    { 
     PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value); 
     // ignore case for the following 
     object originalValue = properties.Find(OriginalProperty, true).GetValue(value); 
     object confirmValue = properties.Find(ConfirmProperty, true).GetValue(value); 
     return Object.Equals(originalValue, confirmValue); 
    } 
} 

는 모델 클래스의 속성에 넣어보다는, 당신은 클래스 자체에 넣어 : 그 샘플 코드는 다음과 같습니다 "사용자 정의 속성에서 호출되면 전체 모델 인스턴스가 전달되어 종속 속성 값을 그렇게 얻을 수 있습니다. 이 패턴을 쉽게 따라 가면서보다 일반적인 비교 속성을 만들 수도 있습니다.

관련 문제