data-annotationsasp.net-mvc-validation

MVC5: Custom validations are not triggered when Submit button is clicked


I am creating a selection screen, let say there are two fields "Start Date" and "End Date" and a "Search" button.

I created custom attribute for validating the date fields such that it must fall within a dynamic date range:

public class YearTimeFrameAttribute : ValidationAttribute
{
    private DateTime _minDate;

    public YearTimeFrameAttribute(int timeFrameInYear)
    {
        int _timeFrame = Math.Abs(timeFrameInYear) * -1;
        _minDate = DateTime.Now.AddYears(_timeFrame);
    }

    public override bool IsValid(object value)
    {
        DateTime dateTime = Convert.ToDateTime(value);
        if (dateTime < _minDate)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    public override string FormatErrorMessage(string name)
    {
        return String.Format("The field {0} must be >= {1}", name, _minDate.ToString("dd/MM/yyyy"));
    }

}

Below is the code in the selection screen model:

public class SelectionParametersModel
{
    [YearTimeFrame(7)]
    [DataType(DataType.Date)]
    [Display(Name = "Extraction Start Date")]
    public DateTime StartDate { get; set; }

    [YearTimeFrame(7)]
    [DataType(DataType.Date)]
    [Display(Name = "Extraction End Date")]
    public DateTime EndDate { get; set; }
}

Finally my controller do this (I am trying to return a file):

    // GET: /SelectionScreen/
    public ActionResult SelectionScreen()
    {
        ViewBag.Title = "Selection Screen";
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult SelectionScreen(SelectionParametersModel selectionParameter)
    {
        ... Code to build report ...

        string mimeType;
        Byte[] renderedBytes;
        Functions.GenerateReport(out renderedBytes, out mimeType);
        return File(renderedBytes, mimeType);
    }

So I input a wrong date in the start/end date fields and click "Search", the program just ignore the validations and generate the file.

(Note: I haven't paste all my code here to keep thing simpler, but I have proved that the date validation logic is correct.)


Solution

  • Sorry that I find my solution shortly after posting the question. (I am really new in MVC)

    I find that I should include "if (ModelState.Isvalid)" in the HttpPost method.

    [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult SelectionScreen(SelectionParametersModel selectionParameter)
        {
            if (ModelState.IsValid)
            {
                ... Code ....
            }
    
            return View();
        }