Home > Back-end >  How to add custom date format validation for DateTime in c#? [duplicate]
How to add custom date format validation for DateTime in c#? [duplicate]

Time:09-21

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?

CodePudding user response:

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

CodePudding user response:

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

  • Related