Passing data from a model to a custom validation class

I have a data validation class that checks to see if the meeting start date is before the end date.

The model automatically changes to a date that requires verification, but I have a slight problem with the transfer of data that needs to be verified.

Here is 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 is a class containing data annotations

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

And here is 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);
    }
+3
source share
1 answer

Validation attributes that work with multiple properties should be applied to the model, and not for 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; }
}
+3
source

Source: https://habr.com/ru/post/1762821/


All Articles