Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC DateTime validation failing

I found a lot of simulair questions but not a good clean solution that is working. I see a lot of custom code for getting this to work but why is that? Should this not working from the start?

What I think is strange, is that in IE9 it works but in Firefox and Chrome it is failing. Everytime that im trying in Firefox or Chrome, I get the message "The field Birthday must be a date".

When I try the code below in a new MVC 4 RTM project, I can't get it to work. I see the DateTime.Now default as dd-MM-yyyy (Holland) in all the browsers but I can't submit it in Firefox and Chrome.

The globalization tag isn't set in web.config so it must be using the default. Im from Holland so it should get the client culture I guess.

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);
    }

Markup

<!-- 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")
}
like image 268
LockTar Avatar asked Aug 24 '12 07:08

LockTar


2 Answers

I was able to fix this by modifying the jQuery validator function for dates:

 <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;
        },
        ''
    );

});

like image 184
gls123 Avatar answered Sep 21 '22 12:09

gls123


The problem was jQuery validation and localization. It seems that there are localization files for messages and methods of the jQuery plugin. See my blog for a detail explaination of the problem and how I solved it.

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

Edit: I just released a new blog post with a refresh of all the localization problems and how to fix it for a DateTime property. See my new post MVC localization validation.

like image 29
LockTar Avatar answered Sep 19 '22 12:09

LockTar