2016-09-12 4 views
0

DataAnnotations를 사용하여 유효성 검사를 처음 사용했습니다. 그러나 나는 단지 모바일이 필요한 환자 객체에 대해, 모바일 오피스가 요구되는 의사 개체에 대한 고려, 이제 등, ASP/MVCDataAnnotation 속성 유효성 검사를 조건부로 켜기/끄기

public class Phone 
{ 
    [Required] 
    public string Mobile { get; set; } 

    [Required] 
    public string Office { get; set; } 
} 

public class Physician 
{ 
    [Required] 
    public Phone ContactPhone { get; set; } 
} 

public class Patient 
{ 
    [Required] 
    public Phone ContactPhone { get; set; } 
} 

을 콘솔 응용 프로그램에서이를 사용, 그래서 아니에요. 주어진 조건에 따라 유효성 검사 속성 동작을 설정/해제하려면 어떻게합니까?

답변

0

PhysicianPatient 클래스는 Phone 클래스 내부에서 무엇이 필요한지 결정해야합니다. 먼저 주석을 사용하지 않고 대신 IValidatableObject 인터페이스를 사용하면됩니다. Validator 클래스는 추가 유효성 검사를 위해이 인터페이스를 검사합니다. 더 의미

public class Phone 
{ 
    // no more required attributes here 
    public string Mobile { get; set; } 

    public string Office { get; set; } 
} 

public class Physician : IValidatableObject 
{ 
    [Required] 
    public Phone ContactPhone { get; set; } 

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
    { 
     if(string.IsNullOrWhiteSpace(ContactPhone.Mobile)) 
     { 
      yield return new ValidationResult("Mobile number is required"); 
     } 

     if (string.IsNullOrWhiteSpace(ContactPhone.Office)) 
     { 
      yield return new ValidationResult("Office number is required"); 
     } 
    } 
} 

public class Patient : IValidatableObject 
{ 
    [Required] 
    public Phone ContactPhone { get; set; } 

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
    { 
     if (string.IsNullOrWhiteSpace(ContactPhone.Mobile)) 
     { 
      yield return new ValidationResult("Mobile number is required"); 
     } 
    } 
} 
+0

감사합니다. – zorrinn

관련 문제