3

I have a model with a StartTime date and an EndTime date :

[Required]
[DataType(DataType.DateTime)]
public DateTime StartTime { get; set; }

[Required]
[DataType(DataType.DateTime)]
public DateTime EndTime { get; set; }

The current view which uses these two dates has the following form :

@if (Roles.IsUserInRole("Teacher"))
{
    <h2>AddSession</h2>

    using (Html.BeginForm("SessionAdded", "Course", FormMethod.Post, new { id = "myform" }))
    {
        @Html.ValidationSummary(true)
        <fieldset>
            <legend>Add Session</legend>
            <div class="editor-label">
                @Html.LabelFor(model => model.Name)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)
            </div>
            <div class="editor-label">
                @Html.LabelFor(model => model.StartTime)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(model => model.StartTime, new { @class = "date" , id = "StartTime" })
                @Html.ValidationMessageFor(model => model.StartTime)
            </div>
            <div class="editor-label">
                @Html.LabelFor(model => model.EndTime)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(model => model.EndTime, new { @class = "date", id = "EndTime" })
                @Html.ValidationMessageFor(model => model.EndTime)
            </div>
            <p>
                <input id="submit" type="submit" />
            </p>
        </fieldset>
    }
}

When I remove : <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> from my view I have no problem.

But when I use jquery.validate, my two fields return: Please enter a valid date.. I use the DateTimePicker for jQuery UI.

I have the follow Javascript code :

$(document).ready(function () {

var datepickers = $('.date').datetimepicker({
    minDate: 0,
    dateFormat: "dd/mm/yy",
    timeFormat: "hh:mm",
    onSelect: function (date) {
        var option = this.id == 'StartTime' ? 'minDate' : 'maxDate';
        datepickers.not('#' + this.id).datepicker('option', option, date);
    }
});

$("#myform").validate({
    ignore: ".date"
})

});

I would like to ignore jQuery validation for my two Date fields (class="date") because it checks for a specific dateformat and I have to use this one in my app : dd/mm/yyyy hh:mm.

I also tried to do a custom validator but without success. I always get the Please enter a valid date error...

Thanks for your help,

Ed

2 Answers 2

2

I have done this and struggled to get it to work across browsers for multiple client locals. If you can definitively say that you only need one date format your can achieve it with the following steps.

Include a Date Editor called Date.cshtml template in your Views\Shared\EditorTemplates folder that looks like this:

@model DateTime?
@Html.TextBox("", Model.HasValue ? Model.Value.ToString("dd/MM/yyyy") : "", new { @class = "date" }) 

Include some javascript to invoke the date picker somewhere sensible, like in a shared layout page or a shared script that looks like this:

$(document).ready(function () {
    $('.date').datepicker({ dateFormat: "dd/mm/yy", firstDay: 1, maxDate: "+0d" });
    $.validator.methods.date = function () { return true; };
});

You may want to change the validator.methods.date function not just to return true but to validate based on your culture requirements

And finally, set your IIS settings to the culture settings, either in the web config, as pollirrata, or this can be done in the IIS admin UI in .Net Globalization settings.

Sign up to request clarification or add additional context in comments.

Comments

1

You may need to change the CurrentCulture to the one you're using as your date format. Hanselman has a nice post about it. Are you using unobtrusive validations included on MVC?

This will be the changes that you'll need to do (in my case the culture is for GB)

web.config

<globalization culture="en-GB" uiCulture="en-GB" enableClientBasedCulture="false" />   

Global.asax

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

Also, you can create an action filter to ensure that the action is getting the culture when submitting

public class CultureAwareActionAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            if (!string.IsNullOrEmpty(filterContext.HttpContext.Request["culture"]))
            {
                Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = new CultureInfo(filterContext.HttpContext.Request["culture"]);
            }
        }
    }

and you will just add the [CultureAwareAction] annotation on your method declaration

(That filter was written for the Telerik team, for handling localization in their controls)

3 Comments

Yes I use unobstrusive validations included on MVC. To be honest I don't really understand where I should change the CurrentCulture in my ASP .NET MVC project.
I tried / <globalization uiCulture="auto:fr-FR" culture="auto:fr-FR" requestEncoding="utf-8" responseEncoding="utf-8" /> In my Web.config but i always get the same error when selecting a DateTime.
I have the same problem :s I'm trying to ignore validation for date fields but doesn't work too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.