ASP.NET MVC自定义验证业务逻辑

时间:2019-03-01 09:58:02

标签: c# asp.net-mvc validation

我正在尝试实现一些自定义验证,但是我在逻辑上有些挣扎。

验证的规则仅是拥有employeeID的员工,在特定日期范围内不能请求多个假期。

例如,如果一名拥有employeeID的员工要求放假StartDate '01 / 01/2019'和FinsihDate '05 / 01/2019'

然后,他们再次请求 StartDate '03 / 01/2019'和{{11} '04 / 01/2019'。

然后验证将处理此问题。

由于我不太熟悉c#

,所以我不确定如何从逻辑的角度实现它
FinsihDate

}

型号:

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

namespace HolidayTracker.Models
{
public class ValidSimilarRequests : ValidationAttribute
{
    private LotusWorksEntities db = new LotusWorksEntities();
    protected override ValidationResult
            IsValid(object value, ValidationContext validationContext)
    {




        var model = (Models.HolidayRequestForm)validationContext.ObjectInstance;

        int empID = Convert.ToInt32(model.EmployeeID);

        DateTime _startdate = Convert.ToDateTime(model.StartDate);
        DateTime _finishdate = Convert.ToDateTime(model.FinishDate);

        var holidayexist = db.HolidayRequestForms.Any()

        if (holidayexist)
        {
            return new ValidationResult
                ("A holiday Request for this date range has already been requested");
        }


        else
        {
            return ValidationResult.Success;
        }


    }
}

1 个答案:

答案 0 :(得分:2)

您可以将其放入“任意”。像这样:

var holidayexist = db.HolidayRequestForms.Any(x=>x.EmpID==empID && x.Startdate>_startdate && x.Enddate < _enddate));

我当然不知道您的HolidayRequestForm对象是如何构建的,希望您能理解我的意思。