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

1
  • 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. Commented Mar 9, 2016 at 23:46

6 Answers 6

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; }
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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);
    }
}

1 Comment

@NET7 contributor
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.

Comments

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

Comments

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; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.