自定义数据验证。第一个输入字段必须低于第二个输入字段

时间:2013-11-28 11:24:48

标签: c# asp.net-mvc

当我有两个输入字段时,如何添加自定义验证,第二个输入字段必须大于第一个输入字段。我想创建一个时间表。例如:一个人可以选择他的工作时间,所以我想确保那个人不能开始工作18.00并完成它(当天)13:00。

有没有“轻松”的方法呢?这是我的Entity类的样子:

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; }
    }
}

感谢您的任何建议:)

3 个答案:

答案 0 :(得分:0)

我认为你应该使用IValidatableObject接口。 您需要在类中实现Validate方法。

答案 1 :(得分: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");
         }
     }

}

答案 2 :(得分: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;
    }
}