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

前端 未结 13 1124
逝去的感伤
逝去的感伤 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:24

    This works for me on both client and server side, I have moment.js installed too.

    $("#datepicker").datepicker();
    $('#datepicker').datepicker("option", "dateFormat", "dd/mm/yy");
    
    $.validator.methods.date = function (value, element) {
        return this.optional(element) || moment(value, "DD/MM/YYYY", true).isValid();
    }
    
    0 讨论(0)
  • 2020-12-29 07:26

    localization or moment.js was not work for me while using datetimepicker. splitting hour and then checking is working. I am using format: 'dd.mm.yyyy hh:ii' for datetimepicker.

    $.validator.methods.date = function (value, element) {
        var dateL = value.split(" ");
        var date = dateL[0].split(".");
        var hour = dateL.length > 1 ? dateL[1].split(":") : "";
        return this.optional(element) || !/Invalid|NaN/.test(dateL.length > 1 ? new Date(date[2], date[1], date[0],hour[0],hour[1]).toString() : new Date(date[2], date[1], date[0]).toString());
    }
    
    0 讨论(0)
  • 2020-12-29 07:28

    I added the fix for date format parser, but I needed to set the format to 'L' so it could be work in all Locales:

    $(function () {
    $.validator.methods.date = function (value, element) {
        return this.optional(element) || moment(value, "L", true).isValid();
    }
    });
    
    0 讨论(0)
  • 2020-12-29 07:29
    1. Install moment.js (Install-Package Moment.js)
    2. Open jquery.validate.js and find the method date: function (value, element)
    3. Replace the content for this:

      var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
      return this.optional(element) || (isChrome ? moment(value, 'L').isValid() : !/Invalid|NaN/.test(new Date(value)));
      
    4. Done
    0 讨论(0)
  • 2020-12-29 07:30

    I have to validate dd/mm/yyyy hh:ii and with help of @lukyer answer i have added DD/MM/YYYY HH:mm and it is working fine Hope this help !

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

    if you use JQuery unubtrosive validation you can add rules like behind and to change client-side validation message.

    $('#inputName').rules('add',{
       messages:{
           date:'Invalid format date'
       }
    })
    
    0 讨论(0)
提交回复
热议问题