Home > Blockchain >  C# model validation shows valid Date range as invalid
C# model validation shows valid Date range as invalid

Time:09-22

My model has a date field like this:

[Display(Name = "Date of Birth")]
[Required(AllowEmptyStrings = false, ErrorMessage = "This field is required.")]
[Range(typeof(DateTime), "1/1/2000", "1/1/2010", ErrorMessage = "Date is out of Range")]
public string DOB { get; set; }

In my view I have this field:

@Html.TextBoxFor(m => m.DOB, new { @class = "form-control", @id = "dob", type = "Date" })
@Html.ValidationMessageFor(m => m.DOB)

The date is always invalid, even if the date is within range.

enter image description here


CodePudding user response:

Have you tried to use the validation with a Datetime prop? Something like it:

[Display(Name = "Date of Birth")]
[Required(ErrorMessage = "This field is required.")]
[Range(typeof(DateTime), "1/1/2000", "1/1/2010", ErrorMessage = "Date is out of Range")]
[DataType(DataType.Date)]
public DateTime DOB { get; set; } 

CodePudding user response:

You DOB is a string type, but you trying to validate DateTime type. You can make a custom validator or you can try to make working something like this

public string DOB 
{
get {  return DOBDateTime.ToString("dd/MM/yyyy HH:mm:ss"); }
set  { DobDateTime= DateTime.Parse(value);  }
}


[NotMapped]

[Display(Name = "Date of Birth")]
[Required(ErrorMessage = "This field is required.")]
[Range(typeof(DateTime), "1/1/2000", "1/1/2010", ErrorMessage = "Date is out of Range")]
[DataType(DataType.Date)]
public DateTime DOBDateTime { get; set; } 

in this case you will have to use DOBDateTime for the user interface only

  • Related