2013-11-28 1 views
0

두 개의 입력 필드가 있고 두 번째 입력 필드가 첫 번째 입력 필드보다 커야 만 사용자 정의 유효성 검사를 추가하는 방법. 나는 일정을 만들고 싶다. 예를 들면 다음과 같습니다. 한 사람이 근무 시간을 선택할 수 있으므로 직원이 18:00에 작업을 시작하고 13:00에 끝내기를 원합니다.사용자 지정 데이터 유효성 검사. 첫 번째 입력 필드는 두 번째 입력 필드보다 낮아야합니다.

"쉬운 방법"이 있습니까? 여기 내 엔티티 클래스처럼 보이는 방법 :

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.ComponentModel; 
using System.ComponentModel.DataAnnotations; 

namespace HospitalSite.Database.Entities 
{ 
    public class Schedule 
    { 
     public int Id { get; set; } 
     public virtual Doctor doctor { get; set; } 

     [DisplayName("Monday")] 
     public bool Monday { get; set; } 

     [DisplayName("Tuesday")] 
     public bool Tuesday { get; set; } 

     [DisplayName("Wednesday")] 
     public bool Wednesday { get; set; } 

     [DisplayName("Thursday")] 
     public bool Thursday { get; set; } 

     [DisplayName("Friday")] 
     public bool Friday { get; set; } 

     //Doctor working hours 
     [Required(ErrorMessage= "Input required for working hours")] 
     [Range(8.00, 18.00, ErrorMessage="Time must be between 8.00 and 18.00")] 
     public int BeginWork { get; set; } 

     [Required(ErrorMessage = "Input required for working hours")] 
     [Range(8.00, 18.00, ErrorMessage = "Time must be between 8.00 and 18.00")] 
     public int EndWork { get; set; } 
    } 
} 

어떤 제안 주셔서 감사합니다 :)

답변

0

당신이 뭔가를 할 수 있습니다 :

또한
public class Schedule 
{ 
    ... 
    public int BeginWork { get; set; } 
    public int EndWork { get; set; } 



    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
    { 
     if (BeginWork >= EndWork) 
     { 
      yield return new ValidationResult("The end work needs to be later than the begin work"); 
     } 
    } 

} 
0

난 당신이 IValidatableObject 인터페이스를 사용한다고 생각합니다. 클래스에 Validate 메서드를 구현해야합니다. 정수와 작업하는 경우

0

당신은 당신의 자신의 사용자 정의 속성을 사용할 수 있습니다 ... 여기 당신은 예를 가지고 :

 

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] 
public sealed class EndWorkNeedToBeLaterThanBeginWorkValidationAttribute : ValidationAttribute 
{ 

    public EndWorkNeedToBeLaterThanBeginWorkValidationAttribute() 
     : base("The end work needs to be later than the begin work") 
    { 
    } 

    protected override ValidationResult IsValid(object value, ValidationContext context) 
    { 
     var endWorkProperty = context.ObjectType.GetProperty("EndWork"); 
     var beginWorkProperty = context.ObjectType.GetProperty("BeginWork"); 

     var endWorkValue = endWorkProperty.GetValue(context.ObjectInstance, null); 
     var beginWorkValue = beginWorkProperty.GetValue(context.ObjectInstance, null); 


     if (beginWorkValue >= endWorkValue) 
     { 
      return new ValidationResult("The end work needs to be later than the begin work", new List { "EndWork", "BeginWork" }); 
     } 

     return ValidationResult.Success; 
    } 
} 
관련 문제