简体   繁体   中英

Validation failing because of date format

I have an MVC6 Edit View with a date of birth field as follows:

<div class="form-group">
    @Html.LabelFor(model => model.DateOfBirth, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @*@Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.DateOfBirth, "", new { @class = "text-danger" })*@
        @Html.EditorFor(m => m.DateOfBirth,new { htmlAttributes = new { @readonly = "readonly" } })
        @Html.ValidationMessageFor(model => model.DateOfBirth, "", new { @class = "text-danger" })
    </div>
</div>

Therefore when I click save it errors saying: The value '07/17/1981' is not valid for ApplicationDate. How can I ensure that the date is displayed in UK format meaning validation succeeds.

I have added the following to the Bubdle.Config following an answer below:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js",
                        "~/Scripts/globalize.js",
                        "~/Scripts/jquery.validate.globalize.js"));

Update your model like this:

// Add this attribute
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] 
public  DateTime DateOfBirth { get; set; }

I'm assuming your error is client-side? ie Unobtrusive validation? An alternative solution to the one already posted is to use the Globalization.

There is a Nuget package available "jQuery.Validation.Globalize. You can install this and simply include the globalize Javascript files with your jqueryval bundles.

You can do this by navigation to the App_Start directory and editing the BundleConfig.cs file. You'll see there should already be a ScriptBundle for bundles/jqueryval - You can add the path to the globalize.js and jquery.val.globalize.js files to that, or create a separate ScriptBundle to reference in your View.

Note: This will only work if you add the CultureInfo to your Global.asax file as below.

You'll also need to add the below to your Global.asax file.

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");

In the director Views/Shared/EditorTemplates I added a view UKDate .

The code for my particular view is:

@model DateTime?

@{
    if (Model.HasValue)
    {
        var classname = ViewData["class"];
        var id = ViewData["id"];

        <input type="text"
               name="@ViewData.TemplateInfo.HtmlFieldPrefix" //this needed to map the input to the property in your model, by the default model binder.
               value="@Model.Value.ToString("dd/MM/yyyy")" 
               class="@classname"
               id="@id"
            />
    }
}

Then to use it I do the following:

@Html.EditorFor(x => x.YourDateFieldDate, "UKDate", new { @class = "any css classes required here", id = "Id here" })

As there is now no data-val-date attribute the validation is not run. So this solves the problem if you don't care about any client side date validation.

Take a look to the example on this page, check if it does what you want.

https://johnnyreilly.github.io/jQuery.Validation.Unobtrusive.Native/AdvancedDemo/Globalize.html

I saw you asked why you need to include jquery, the answer is because microsoft validation happens thanks to jquery, they work together to achieve this.

If you page is english en-US, default validation will work, but if your culture is different like mine, you need at least to include what is mentioned in that page (basically jquery, globalize and validation).

Globalize will override Validation to work in your desired culture.

Give it a try and let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM