ASP.NET MVC2 Model Validation Fails with Non-US Date Format

爱⌒轻易说出口 提交于 2019-12-04 06:36:53

Here's how I solved the issue in my case. I manually validated the date in the controller and reset the ModelState for that property:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Save(TestViewModel model) {

    var tempDate = new DateTime();
    var culture = CultureInfo.CurrentUICulture;

    if(DateTime.TryParse(Request.Form["TheDate"], culture, DateTimeStyles.None, out tempDate)) {
        model.DateOfBirth = tempDate;
        ModelState.Remove("TheDate");
        }

    if(ModelState.IsValid) {  // <--- Now valid
        // Do other stuff
        return this.View("Complete", model);
        }

    // Validation failed, redisplay the form.
    return this.View("Enter", model);
    }

The validation occurs within the DataAnnotations class. You can subclass DataAnnotations classes for your own purposes.

I would create a new MultiCultureDateType DataAnnotations class that will validate dates across multiple cultures.

More information: http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx

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