Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data Annotation Ranges of Dates

Is it possible to use [Range] annotation for dates?

something like

[Range(typeof(DateTime), DateTime.MinValue.ToString(), DateTime.Today.ToString())]
like image 417
Davy Avatar asked Sep 10 '09 15:09

Davy


People also ask

What is range attribute?

The range attribute allows a numeric range to be specified for a slot when a numeric value is used in that slot. If a numeric value is not used in that slot, then no checking is performed.

What is data annotation in C# example?

Data annotations (available as part of the System. ComponentModel. DataAnnotations namespace) are attributes that can be applied to classes or class members to specify the relationship between classes, describe how the data is to be displayed in the UI, and specify validation rules.

What is data annotation attribute?

We'll use the following Data Annotation attributes: Required – Indicates that the property is a required field. DisplayName – Defines the text to use on form fields and validation messages. StringLength – Defines a maximum length for a string field. Range – Gives a maximum and minimum value for a numeric field.

Which namespace is used for data annotation?

ComponentModel. DataAnnotations Namespace. Provides attribute classes that are used to define metadata for ASP.NET MVC and ASP.NET data controls.


2 Answers

I did this to fix your problem

 public class DateAttribute : RangeAttribute    {       public DateAttribute()         : base(typeof(DateTime), DateTime.Now.AddYears(-20).ToShortDateString(),     DateTime.Now.AddYears(2).ToShortDateString()) { }     } 
like image 139
MarkKGreenway Avatar answered Sep 17 '22 17:09

MarkKGreenway


Docs on MSDN says you can use the RangeAttribute

[Range(typeof(DateTime), "1/2/2004", "3/4/2004",
        ErrorMessage = "Value for {0} must be between {1} and {2}")]
public datetime Something { get; set;}
like image 30
Daniel Elliott Avatar answered Sep 20 '22 17:09

Daniel Elliott