MVC DateTime验证失败

时间:2012-08-24 07:58:40

标签: asp.net-mvc asp.net-mvc-3 validation asp.net-mvc-4 model-validation

我发现了很多simulair问题但不是一个有效的干净解决方案。我看到很多自定义代码可以让它工作,但为什么会这样?这应该从一开始就不起作用吗?

我认为奇怪的是,在IE9中它可以运行但在Firefox和Chrome中却失败了。 每当我在Firefox或Chrome中尝试时,我都会收到消息“字段生日必须是日期”。

当我在新的MVC 4 RTM项目中尝试下面的代码时,我无法让它工作。我在所有浏览器中都看到DateTime.Now默认为dd-MM-yyyy(Holland)但我无法在Firefox和Chrome中提交它。

全球化标记未在web.config中设置,因此必须使用默认值。我来自荷兰,所以它应该得到我想的客户文化。

public class RegisterModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
    //[DataType(DataType.Date)]
    public DateTime Birthday { get; set; }
}

[AllowAnonymous]
    public ActionResult Register()
    {
        RegisterModel vm = new RegisterModel()
        {
            Birthday = DateTime.Now
        };
        return View(vm);
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            try
            {
                //WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                //WebSecurity.Login(model.UserName, model.Password);
                return RedirectToAction("Index", "Home");
            }
            catch (MembershipCreateUserException e)
            {
                ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

标记

<!-- language: lang-none -->
@model DateTimeWithDatePicker.Models.RegisterModel
@{
   ViewBag.Title = "Register";
}

<hgroup class="title">
    <h1>@ViewBag.Title.</h1>
    <h2>Create a new account.</h2>
</hgroup>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()

    <fieldset>
        <legend>Registration Form</legend>
        <ol>
            <li>
                @Html.LabelFor(m => m.UserName)
                @Html.TextBoxFor(m => m.UserName)
            </li>
            <li>
                @Html.LabelFor(m => m.Birthday)
                @Html.EditorFor(m => m.Birthday)
            </li>
        </ol>
        <input type="submit" value="Register" />
    </fieldset>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

3 个答案:

答案 0 :(得分:7)

我能够通过修改日期的jQuery验证器函数来解决这个问题:

 <script type="text/javascript">

  $(function () {

    var dateFormat="dd/mm/yy"; // en-gb date format, substitute your own

    $("#Birthday").datepicker({
        "dateFormat": dateFormat
    });

    jQuery.validator.addMethod(
        'date',
        function (value, element, params) {
            if (this.optional(element)) {
                return true;
            };
            var result = false;
            try {
                $.datepicker.parseDate(dateFormat, value);
                result = true;
            } catch (err) {
                result = false;
            }
            return result;
        },
        ''
    );

});

答案 1 :(得分:3)

问题是jQuery验证和本地化。似乎有jQuery插件的消息和方法的本地化文件。请参阅我的博客,详细解释问题以及我是如何解决的。

http://www.locktar.nl/programming/mvc/localization-validation-in-mvc/

修改 我刚刚发布了一篇新的博客文章,刷新了所有本地化问题以及如何为DateTime属性修复它。请参阅我的新帖子MVC localization validation

答案 2 :(得分:1)

  

全球化标记未在web.config中设置,因此必须使用   默认。我来自荷兰,所以它应该得到我想的客户文化。

不,那不对。你可以从荷兰完全没问题,并将你的浏览器配置为使用中国文化。你不能让它工作的原因可能是因为在FF和Chrome中你没有正确的文化。

由于您尚未在web.config中的全球化元素中指定文化,因此ASP.NET MVC将使用请求标头中从浏览器发送的文化。例如,如果您将浏览器配置为en-US文化,则将在每个请求中设置以下标头:

Accept-Language:en-US,en;q=0.8

以下是Chrome中的配置方式:

enter image description here

因此,请确保您已将所需的语言放在列表中。

如果您想在模型绑定期间使用与DisplayFormat属性中定义的语法相同的语法,可以编写自定义模型绑定器,如下所示:https://stackoverflow.com/a/7836093/29407