1

I have this class overriding the RangeAttribute:

public class RangeDateAttribute : RangeAttribute
{
    public RangeDateAttribute()
        : base(typeof(DateTime),
    DateTime.Now.AddYears(-20).ToShortDateString(), DateTime.Today.ToShortDateString()) { }
}

DataAnnotation for my attribute:

[RangeDate(ErrorMessage = "Value for {0} must be between {1} and {2}")]
public DateTime anyDate { get; set; }

I'm using the method [ToShortDateString()] in that validation, but when displays the error, it comes with the time.. Ex:

Value for anyDate must be between 26/05/1995 00:00:00 and 26/05/2015 00:00:00

How can I solve this?

Thanks.

developer033
  • 24,267
  • 8
  • 82
  • 108

2 Answers2

1

You can use a little formatting on the error message attribute:

[RangeDate(ErrorMessage = "Value for {0} must be between {1:dd/MM/yyyy} and {2:dd/MM/yyyy}")]
public DateTime anyDate { get; set; }
Tran Nguyen
  • 1,341
  • 10
  • 15
  • Works like a charm, thanks a lot! Btw, I don't need to use the ToShortDateString() in that class, right? Just in the Error message.. – developer033 May 27 '15 at 02:08
  • You still need to use ToShortDateString() or ToString() method to convert DateTime to a string because the parameter data type accept string only. Also, you may want to set time value of the maximum parameter to be 23:59:59 instead of 00:00:00 to include the whole day, and you can do that with: DateTime.Today.ToString("dd/MM/yyyy 23:59:59"). Happy coding! – Tran Nguyen May 27 '15 at 02:25
0

You have to format error message using for example, ArgumentException(String) method and apply formatting spec like String.Format("{0:d}", dt) pertinent to short date. Hope this may help. Best regards,

Alexander Bell
  • 7,842
  • 3
  • 26
  • 42