skip to Main Content

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?

2

Answers


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

    Login or Signup to reply.
  2. 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" };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search