how to fix 'The field must be a date' on a datetime property in mvc

前端 未结 13 1123
逝去的感伤
逝去的感伤 2020-12-29 06:59

I need to capture date and time both for my model property. In my model class I have the following

[Required]
[DataType(DataType.DateTime)]
public DateTime?          


        
相关标签:
13条回答
  • 2020-12-29 07:07

    In my case in my Model I had :

    [DisplayFormat(DataFormatString = "{0:dd MMM yyyy}", ApplyFormatInEditMode = true)].
    

    In my view in my script, I had:

        $(function () {
                    $('.datepicker').datepicker({
                        changeMonth: true,
                        changeYear: true,
                        format: "dd MMM yyyy"
                    });
            });

    When I changed my script's format to format: dd M yyyy - it worked.

    0 讨论(0)
  • 2020-12-29 07:08

    In the model for example:

        [Display(Name = "Insert Start Date")]
        [Required(ErrorMessage = "You must specify the date of the event!")]
        [DataType(DataType.DateTime, ErrorMessage = "Podaj prawidłową datę wydarzenia")]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:mm}", ApplyFormatInEditMode = true)]
        public DateTime StartDate { get; set; }
    
        [Display(Name = "Insert End Date")]
        [Required(ErrorMessage = "You must specify the date of the event!")]
        [DataType(DataType.DateTime, ErrorMessage = "Podaj prawidłową datę wydarzenia")]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:mm}", ApplyFormatInEditMode = true)]
        public DateTime EndDate { get; set; }
    

    And View my example code:

    <script>
    $('#startDate').datetimepicker({
        onClose: function (dateText, inst) {
            var endDateTextBox = $('#endDate');
            if (endDateTextBox.val() != '') {
                var testStartDate = new Date(dateText);
                var testEndDate = new Date(endDateTextBox.val());
                if (testStartDate > testEndDate)
                    endDateTextBox.val(dateText);
            }
            else {
                endDateTextBox.val(dateText);
            }
        }, dateFormat: 'yy-mm-dd',
        onSelect: function (selectedDateTime) {
            var start = $(this).datetimepicker('getDate');
            $('#endDate').datetimepicker('option', 'minDate', new Date(start.getTime()));
        }
    }); ....
    

    This caused positive effects: dateFormat: 'yy-mm-dd',

    0 讨论(0)
  • 2020-12-29 07:14
    1. Add following method in the additional-methods.js file and include this file in your project:

          $.validator.addMethod('date',
            function (value, element) {
                if (this.optional(element)) {
                    return true;
                }
                var valid = true;
                try {
                    $.datepicker.parseDate('dd/mm/yy', value);
                }
                catch (err) {
                    valid = false;
                }
                return valid;
            });
    
    1. View must be like this:
           @Html.TextBoxFor(model => model.DOB, new { @class = "datetype", type ="text" })
           @Html.ValidationMessageFor(model => model.DOB)
    
         $(function () {
                  $(".datetype").datepicker({ dateFormat: 'dd/mm/yy' }); 
          });
    

    It works for me.

    0 讨论(0)
  • 2020-12-29 07:16

    You need to make sure your application's Culture is properly set.

    Example

    The following example shows how cultures affect date parsing: https://dotnetfiddle.net/vXQTAZ

    DateTime dateValue;
    string dateString = "28/05/2015 15:55";
    
    if (DateTime.TryParse(dateString, CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.None, out dateValue))
    {
        Console.WriteLine("Valid en-US date.");
    }
    else
    {
        Console.WriteLine("Not a valid en-US date.");
    }
    
    if (DateTime.TryParse(dateString, CultureInfo.CreateSpecificCulture("fr-FR"), DateTimeStyles.None, out dateValue))
    {
        Console.WriteLine("Valid fr-FR date.");
    }
    else
    {
        Console.WriteLine("Not a valid fr-FR date.");
    }
    

    Output

    Not a valid en-US date.

    Valid fr-FR date.

    Client Side Settings

    You may also need to make sure that your client side validators are using properly cultures/globalization. If you are using jQuery validate plugin with MVC, see this extension to help modify that plugin to meet your needs: http://blog.icanmakethiswork.io/2012/09/globalize-and-jquery-validate.html

    0 讨论(0)
  • 2020-12-29 07:19
    $(function () {
        $.validator.addMethod('date',
        function (value, element) {
            if (this.optional(element)) {
                return true;
            }
            var valid = true;
            try {
                $.datepicker.parseDate('dd/mm/yy', value);
            }
            catch (err) {
                valid = false;
            }
            return valid;
        });
        $(".datetype").datepicker({ dateFormat: 'dd/mm/yy' });
    });
    

    Put this code in a file datepicker.js and include this file in html

    0 讨论(0)
  • 2020-12-29 07:19

    I couln't solve it by the others answers. In my case, using TextBoxFor wasn't mandatory; I used TextBox instead.

    Model

    [Required(ErrorMessage = "Required")]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime MyDate{get;set;}
    

    View

    @Html.TextBox("MyDate", DateTime.Now.ToString(), new {@type="datetime"})
    
    0 讨论(0)
提交回复
热议问题