2013-11-28 78 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接口。 您将需要在您的班级中实施验证方法。

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; 
    } 
} 
相关问题