Passing data from the model into custom validation class

江枫思渺然 提交于 2019-12-23 21:26:33

问题


I have a data validation class that checks whether the start date of a meeting is before the end date.

The model automatically passes in the date that requires validation, but i'm having a bit of difficulty passing the data that it needs to be validated against.

Here's my validation class

sealed public class StartLessThanEndAttribute : ValidationAttribute
    {            
        public DateTime DateEnd { get; set; }

        public override bool IsValid(object value)
        {                
            DateTime end = DateEnd;
            DateTime date = (DateTime)value;

            return (date < end);
        }

        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name);
        }
    }

Here's the class that contains the data annotations

[StartLessThanEnd(ErrorMessage="Start Date must be before the end Date")]
public DateTime DateStart { get; set; }

And here's my controller

[HttpPost, Authorize]
    public ActionResult Create(Pol_Event pol_Event)
    {
        ViewData["EventTypes"] = et.GetAllEventTypes().ToList();

        StartLessThanEndAttribute startDateLessThanEnd = new StartLessThanEndAttribute();


        startDateLessThanEnd.DateEnd = pol_Event.DateEnd;


        if (TryUpdateModel(pol_Event))
        {
            pol_Event.Created_On = DateTime.Now;
            pol_Event.Created_By = User.Identity.Name;

            eventRepo.Add(pol_Event);
            eventRepo.Save();
            return RedirectToAction("Details", "Events", new { id = pol_Event.EventID });
        }

        return View(pol_Event);
    }

回答1:


Validation attributes that work with multiple properties should be applied to the model and not on individual properties:

[AttributeUsage(AttributeTargets.Class)]
public class StartLessThanEndAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var model = (MyModel)value;
        return model.StartDate < model.EndDate;
    }
}

[StartLessThanEnd(ErrorMessage = "Start Date must be before the end Date")]
public class MyModel
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}


来源:https://stackoverflow.com/questions/3626322/passing-data-from-the-model-into-custom-validation-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!