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

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

提交回复
热议问题