自定义验证日期c#

时间:2017-06-29 09:13:37

标签: c# validation datetime data-annotations

我想为datetime字段创建自定义验证。

我的课程预订,我想要验证字段“日期”:

    public class Booking
    {
        public int Id { get; set; }
        public int Restochoisi { get; set; }
        public int Nbpeople { get; set; }
        [CustomValidator]
        public DateTime Date { get; set; }
        public int Orga { get; set; }
    }

CustomValidator.cs类:

    [AttributeUsage(AttributeTargets.Property |
  AttributeTargets.Field, AllowMultiple = false)]
public class CustomValidator : ValidationAttribute
{
    protected override bool IsValid(object value)
    {
        if ((DateTime)value < DateTime.Now)
            return false;
        return true;
    }

}

和BookingController:

    [HttpPost]
    public ActionResult Index(int restochoisi, int nbpeople, DateTime start, int orga)

    {
        var context = new BddContexte();

        var vm = new BookingViewModel()
        {
            Restos = new SelectList(context.Restos.AsEnumerable(), "Id", "Nom"),
            Utilisateurs = new SelectList(context.Utilisateurs.AsEnumerable(), "Id", "Prenom")

        };

        //ViewBag.result = restochoisi + " " + nbpeople + " " + datepicker + " " + orga;
        //dal.RestoById(restochoisi)
        if (ModelState.IsValid)
        {
            int id = dal.CreerBooking(restochoisi, nbpeople, start, orga);
            return View(vm);
        }
        return View(vm);
    }

但它不起作用。我的步态出了什么问题?

1 个答案:

答案 0 :(得分:0)

您的控制器应使用带有验证器的模型类

[HttpPost]
public ActionResult Index(Booking booking)
{
     // snip
}

没有它,我不确定您认为自定义验证器的工作方式是什么?!