Customize the Error Message MVC for an invalid DateTime in ASP.NET MVC4

后端 未结 5 1255
不知归路
不知归路 2020-12-23 15:20

I am having trouble specifying the error message for the validation of a DateTime input value using data annotations in my model. I would really like to use the proper DateT

5条回答
  •  时光说笑
    2020-12-23 15:42

    I got around this issue by modifying the error in the ModelState collection at the start of my action method. Something like this:

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult MyAction(MyModel model)
        {
            ModelState myFieldState = ModelState["MyField"];
            DateTime value;
            if (!DateTime.TryParse(myFieldState.Value.AttemptedValue, out value))
            {
                myFieldState.Errors.Clear();
                myFieldState.Errors.Add("My custom error message");
            }
    
            if (ModelState.IsValid)
            {
                // Do stuff
            }
            else
            {
                return View(model);
            }
        }
    

提交回复
热议问题