2017-04-11 1 views
0

asp.net 핵심 웹 API를 사용하여 모델을 만들었으며 속성을 확인하려면 bool 데이터 유형 속성 값에 따라 유효성을 검사해야합니다.모델의 유효성 검사 방법 asp.net 핵심 웹 API를 사용하는 bool 데이터 유형 값에 따라 달라짐

IsWaitingList 속성이 true이면 WaitingListEncounterOrOtherEncounter 속성이 필수 속성이며, 그렇지 않으면 필수 필드가 아닙니다.

public class CenterConfiguration 
    { 
     public Guid Id { get; set; } = Guid.NewGuid(); 
     public bool? IsWaitingList { get; set; } 
     [Required(ErrorMessage = "Please enter waiting list encounter or other encounter")] 
     public int WaitingListEncounterOrOtherEncounter { get; set; } 
    } 

아무도 모른다면 알려 주시기 바랍니다.

답변

1

IValidatableObject을 구현하여 복잡한 유효성 검사 조건을 확인할 수 있습니다.

public class CenterConfiguration : IValidatableObject { 
    public Guid Id { get; set; } = Guid.NewGuid(); 
    public bool? IsWaitingList { get; set; } 
    public int? WaitingListEncounterOrOtherEncounter { get; set; } 

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { 
     if (IsWaitingList && !WaitingListEncounterOrOtherEncounter.HasValue) { 
      yield return new ValidationResult(
       "Please enter waiting list encounter or other encounter", 
       new[] { "WaitingListEncounterOrOtherEncounter" } 
      ); 
     } 
    } 
} 

또한 내가 그렇게 당신이 실제로이 값을 비워 둘 수 있습니다 int?int에서 WaitingListEncounterOrOtherEncounter을 변경 있습니다.

도 참조 How do I use IValidatableObject?

관련 문제