Search code examples
c#asp.net-coreasp.net-core-mvcrazor-pages

Required error message not displaying for date Time field


I have the following Model:

public partial class EmployeeInfo   
{
    public int EmployeeInfoId { get; set; }
    
    [DisplayName("DOB")]
    [Required(ErrorMessage = "Birthdate is required. [MM/DD/YYYY]")]
    public DateTime DateOfBirth { get; set; } 
}

This is what I have on my cshtml page:

<div class="form-group row">
                    <div class="col-sm-4">
                        <label asp-for="DateOfBirth" class="control-label required" style="font-weight:bold;"></label>
                        <input class="form-control input-lg" required name=x size=10 maxlength=10 onkeydown="this.value=this.value.replace(/^(\d\d)(\d)$/g,'$1/$2').replace(/^(\d\d\/\d\d)(\d+)$/g,'$1/$2').replace(/[^\d\/]/g,'')" />
                        <span asp-validation-for="DateOfBirth" class="text-danger"></span>
                    </div>

I cannot put type="date" for this field because user does not want to see the calendar . How can I see the validation error message for date of birth field since I am not putting type="date". I still want to see the error message saying "DOB is required", but I dont see any message.

Any help will be greatly appreciated.


Solution

  • Try making the property nullable:

    public partial class EmployeeInfo   
    {    
        [DisplayName("DOB")]
        [Required(ErrorMessage = "Birthdate is required. [MM/DD/YYYY]")]
        public DateTime? DateOfBirth { get; set; } 
    }
    

    AFAIK validation works with the EmployeeInfo, not the posted data and since DateTime is value type it will be initialized with default value which is not empty.