19

I'm using Bootstrap 3 Datepicker (http://eonasdan.github.io/bootstrap-datetimepicker/) to present a DateTime Picker for a model property:

Model:

[Table("Calls")]
public partial class Call
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required(ErrorMessage = "Campo obrigatório")]
    [Display(Name = "Data e Hora de início")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MM-yyyy HH:mm}")]
    public DateTime DateOfTheCall { get; set; }
}

View:

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

I set the datepicker with the date format:

// initialise any date pickers
$('.date').datetimepicker({
    locale: 'pt',
    format: 'DD-MM-YYYY HH:mm'
});

I also set the culture in the web.config file:

<globalization culture="pt-PT"/>

But I'm always getting the error message:

The field Data e Hora de início must be a date.
Patrick
  • 2,995
  • 14
  • 64
  • 125
  • 1
    You can validate your datetimepicker through javascript, create a function that would check the value,. – kwingkwingko Dec 08 '15 at 05:49
  • 1
    I think your @Html.EditorFor is generating as textbox with type='textbox' but it should be type='date'. This might can help you – Nimmi Dec 08 '15 at 07:02
  • 1
    @Nimmi Hi thanks, how do I change the type of the EditorFor? – Patrick Dec 08 '15 at 12:42
  • 1
    @KK.K Hi thanks, the datepicker already do the validation, the problem is the definition is the model with the type Datetime – Patrick Dec 08 '15 at 12:43
  • 1
    Hi, I am a UI person not so good in C# but this link might can help you to change type : http://stackoverflow.com/questions/10251153/how-to-get-a-datepicker-for-html-editorfor – Nimmi Dec 09 '15 at 06:20
  • 1
    @Patrick, you can validate a datetimepicker without using the model, just the javascript itself. – kwingkwingko Dec 09 '15 at 08:35
  • 1
    @KK.K And how do you define the property in the class? – Patrick Dec 09 '15 at 14:35
  • 1
    You can also add that in javascript by using the method addClass(); ^_^ – kwingkwingko Dec 10 '15 at 08:27

2 Answers2

8

After a lot of hours, I finally found a way to create a good solution, based on the jQuery Validation Globalize Plugin:

This extension has the following dependencies:

  • jQuery Validation (which itself depends on jQuery)
  • Globalize v1.x (which itself depends on CDLR)

The final code

First, include the libraries (respect the order):

<script src="~/Scripts/cldr.js"></script>
<script src="~/Scripts/cldr/event.js"></script>
<script src="~/Scripts/cldr/supplemental.js"></script>
<script src="~/Scripts/cldr/unresolved.js"></script>
<script src="~/Scripts/globalize.js"></script>
<script src="~/Scripts/globalize/number.js"></script>
<script src="~/Scripts/globalize/date.js"></script>
<script src="~/Scripts/moment.min.js"></script>
<script src="~/Scripts/moment-with-locales.min.js"></script>
<script src="~/Scripts/bootstrap/bootstrap.js"></script>
<script src="~/Scripts/respond/respond.js"></script>
<script src="~/Scripts/jquery/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery/jquery.validate.globalize.min.js"></script>
<script src="~/Scripts/bootstrap-datetimepicker.js"></script>

I use the Module Pattern for script:

// Module Pattern
// More information: http://toddmotto.com/mastering-the-module-pattern/

var Layout = (function ($) {
    // Prevents certain actions from being taken and throws exceptions
    "use strict";

    // Private functions
    var _init = function () {

        // Use $.getJSON instead of $.get if your server is not configured to return the
        // right MIME type for .json files.
        $.when(
            $.getJSON("/Scripts/cldr/supplemental/likelySubtags.json"),
            $.getJSON("/Scripts/cldr/main/numbers.json"),
            $.getJSON("/Scripts/cldr/main/ca-gregorian.json"),
            $.getJSON("/Scripts/cldr/supplemental/timeData.json")
        ).then(function () {

            // Normalize $.get results, we only need the JSON, not the request statuses.
            return [].slice.apply( arguments, [ 0 ] ).map(function( result ) {
                return result[ 0 ];
            });

        }).then( Globalize.load ).then(function() {

            // Your local settings code goes here.
            Globalize.locale("pt-PT");
        });

        // initialise any date pickers (I had my own properties)
        $('.date').datetimepicker({
            locale: 'pt',
            format: 'DD-MM-YYYY HH:mm',
            sideBySide: true,
            showClose: true,
            defaultDate: new Date(Date.now()),
            toolbarPlacement: 'top',
            showTodayButton: true,
            showClear: true,
        });
    };

    return {

        // Public functions
        init: _init

    };

})(jQuery);

// Load when ready
$(document).ready(function () {
    Layout.init();
});

The view remain the same.

Patrick
  • 2,995
  • 14
  • 64
  • 125
1

I think locale : "pt" is mentioned wrongly. Please remove it and test.

Please read below:

enter image description here

Alpesh Panchal
  • 1,723
  • 12
  • 9
  • 1
    Hi, thank you for your help but I tried your solution and I was not able to put it running. You can check mine to see if you agree with it. – Patrick Dec 14 '15 at 14:38