1

I want to add validation to my date property to my class in my c# class.

public class Item
{
    [Required]
    public DateTime RecDate { get; set; }
}

But RecDate property sholud only accept the format "yyyyDDmm". For example 20211709.

If type another format, it should return error when I validate the Item object.

How can I set the validation format?

barteloma
  • 6,403
  • 14
  • 79
  • 173
  • I think you might need to introduce an other string property and annotate that with a [RegularExpressionAttribute](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.regularexpressionattribute). And you can use that as the `setter`, whereas the `RecDate` becomes a calculated property. – Peter Csala Sep 17 '21 at 12:55
  • RecDate is a DateTime. A DateTime is a DateTime and has no specific string format. yyyyDDmm is just a string display format which you can use Parse, ParseExact, TryParse to parse it into a DateTime. You are describing ParseExact. You better use a control like DateTimePicker. ie: var myDate = DateTime.ParseExact("20213101", "yyyyddMM",null); – Cetin Basoz Sep 17 '21 at 13:03
  • How to do this is explained in detail [here](https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings). – Robert Harvey Sep 17 '21 at 13:16

2 Answers2

1

You can achieve this by registering a custom model binder for dates in your global.asax and specify the format you want to use there:

ModelBinders.Binders[typeof(DateTime)] = 
       new DateAndTimeModelBinder() { CustomFormat = "yyyyDDmm" };
Richard Garside
  • 87,839
  • 11
  • 80
  • 93
0

You could use extension methods to format it with an IFormatProvider or a string, and implement the formatting validation if you want.

  • That's an interesting clue, but it doesn't explain how to do it. Extension methods are just syntactic sugar for static methods, so I don't really see how that pertains, other than convenience. – Robert Harvey Sep 17 '21 at 13:15
  • then you could create a private method to validate the datetime, somehow. that strongly depends on your needs, or why are you trying to constrain the formatting. – Rafaelplayerxd YT Sep 17 '21 at 13:18