2

The RequiredAttribute works for string but not DateTime. For example:

    [Required]
    [DisplayFormat(ConvertEmptyStringToNull = false)]
    public string Name { get; set; }

    [Required]
    [DataType(DataType.DateTime)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MMM-yyyy}", ConvertEmptyStringToNull = false)]
    public DateTime Birthdate { get; set; }

If Name is empty the Validation shows error, but if Birthdate is empty then nothing happens. I looked at:

ASP MVC 5 Client Validation for Range of Datetimes

and

MVC Model Range Validator?

but still doesn't work for the DateTime

Community
  • 1
  • 1
user576914
  • 199
  • 1
  • 8
  • 22
  • 3
    The `[Required]` attribute does work for `DateTime` and if you clear the value in the textbox, then a validation message will be shown assuming your view is correct. –  Mar 09 '16 at 23:46

6 Answers6

7

DateTime is a struct, structs are "value type", not "reference type", so their default value are not null, for DateTime it is 1/1/0001 12:00:00 AM, int has its default value as 0.

string type is a "reference type", all reference type have their default value as null.

So if you want to check if a value type is null you should create it as Nullable.

Like this:

public DateTime? Birthdate { get; set; }

Or

public Nullable<DateTime> Birthdate { get; set; }
Vadim Ovchinnikov
  • 13,327
  • 5
  • 62
  • 90
Raphael Ribeiro
  • 529
  • 5
  • 18
5

i think DateTime has a standard value so instead of required you should add a range attribute

[Range(typeof(DateTime), "01/01/1900", "01/01/2100", ErrorMessage="Date is out of Range")]

somthing like this should do the trick

Axel Bouttelgier
  • 173
  • 1
  • 12
4

If you don't want to make DateTime nullable, yet still interpret the default value of 0001-01-01 12:00:00 AM (DateTime.MinValue) as "missing", simply create your own validator:

public class RequiredDateTimeAttribute : ValidationAttribute
{
    public RequiredDateTimeAttribute()
    {
        ErrorMessage = "The {0} field is required";
    }

    public override bool IsValid(object value)
    {
        if (!(value is DateTime))
            throw new ArgumentException("value must be a DateTime object");

        if ((DateTime)value == DateTime.MinValue)
            return false;

        return true;
    }

    public override string FormatErrorMessage(string name)
    {
        return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name);
    }
}
BCA
  • 7,776
  • 3
  • 38
  • 53
1

It is because the Birthdate property is not nullable, so it always will have a value, if changed to:

public Nullable<DateTime> Birthdate { get; set; }

then the required attribute will work as expected.

Martin Staufcik
  • 8,295
  • 4
  • 44
  • 63
1

To expand upon Axel Bouttelgier's answer, the code would look like this:

Server side code

[Display(Name = "Disconnect Service")]
[Range(typeof(DateTime), "01/01/1900", "01/01/2100" )]
public DateTime Disconnect Service { get; set; }

View code

@Html.ValidationSummary()

The validation would look like this: enter image description here

Kellen Stuart
  • 7,775
  • 7
  • 59
  • 82
0

you can use kendo ui component in EditorTemplates and in Date.cshtml then when default date is DateTime.Now

@using Kendo.Mvc.UI
@model DateTime?
    @if (Model.ToString() == "0001-01-01T00:00:00")
    {
        @Html.Kendo().DatePickerFor(m => m).Format("yyyy/MM/dd").HtmlAttributes(new {style = "width: 20em", type = "text" }).Value(DateTime.Now).Footer("Today -  #=kendo.toString(data, 'dddd  yyyy/MM/dd') #")
    }
    else
    {
        @Html.Kendo().DatePickerFor(m => m).Format("yyyy/MM/dd").HtmlAttributes(new {style = "width: 20em", type = "text"}).Value(Model).Footer("Today-  #=kendo.toString(data, 'dddd  yyyy/MM/dd') #")
    }

and in viewmodel class use

[UIHint("Date")]
public DateTime CreateDate { get; set; }