Data Annotation Ranges of Dates
59,298
Solution 1
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;}
Solution 2
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()) { }
}
Solution 3
jQuery validation does not work with [Range(typeof(DateTime),"date1","date2"] -- My MSDN doc is incorrect
Solution 4
Here is another solution.
[Required(ErrorMessage = "Date Of Birth is Required")]
[DataType(DataType.Date, ErrorMessage ="Invalid Date Format")]
[Remote("IsValidDateOfBirth", "Validation", HttpMethod = "POST", ErrorMessage = "Please provide a valid date of birth.")]
[Display(Name ="Date of Birth")]
public DateTime DOB{ get; set; }
The simply create a new MVC controller called ValidationController and past this code in there. The nice thing about the "Remote" approach is you can leverage this framework to handle any kind of validations based on your custom logic.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
namespace YOURNAMESPACEHERE
{
public class ValidationController : Controller
{
[HttpPost]
public JsonResult IsValidDateOfBirth(string dob)
{
var min = DateTime.Now.AddYears(-21);
var max = DateTime.Now.AddYears(-110);
var msg = string.Format("Please enter a value between {0:MM/dd/yyyy} and {1:MM/dd/yyyy}", max,min );
try
{
var date = DateTime.Parse(dob);
if(date > min || date < max)
return Json(msg);
else
return Json(true);
}
catch (Exception)
{
return Json(msg);
}
}
}
}
Solution 5
For those rare occurrences when you are forced to write a date as a string (when using attributes), I highly recommend using the ISO-8601 notation. That eliminates any confusion as to whether 01/02/2004 is january 2nd or february 1st.
[Range(typeof(DateTime), "2004-12-01", "2004-12-31",
ErrorMessage = "Value for {0} must be between {1} and {2}")]
public datetime Something { get; set;}
Author by
Davy
Updated on July 09, 2022Comments
-
Davy almost 2 years
Is it possible to use
[Range]
annotation for dates?something like
[Range(typeof(DateTime), DateTime.MinValue.ToString(), DateTime.Today.ToString())]
-
Davy over 14 yearsThanks Dan - I get an error though and not sure how to fix: 'System.ComponentModel.DataAnnotations.RangeAttribute' does not contain a constructor that takes '0' arguments any idea?
-
Davy over 14 yearsThanks for all your help Dan - That seems to work but I can't substitue theh hardcodes strings for something like DateTime.Now.Date.toString() I get: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type Sry - I'm probably doing something dumb :) Davy
-
Dusda about 13 yearsI am having trouble getting this method to work implicitly with jquery.validate. I get the impression that the range validation doesn't really translate to it?
-
Benk about 12 yearsI have tried doing this: but it doesn't seem to work: any ideas why? [Range(typeof(DateTime),DateTime.Now.AddDays(1).ToShortDateString(), "3/4/2022", ErrorMessage = "Error message here")], I want to validate if the date is choose is less then today's date... thx!
-
Daniel Elliott about 12 yearsBen ... unfortunately in a decorating attribute the values you use must be static and not dynamic. I'd suggest writing your own DataAnnotation if you need it to be dynamic.
-
Alex White over 10 yearsThat MSDN documentation is incorrect if you are using a UK date format - I have an open question on this issue here stackoverflow.com/questions/2251834/…
-
Avrohom Yisroel over 9 yearsJust come across this, and am amazed at how simple but effective it is! Can't believe it has so few votes.
-
Shimmy Weitzhandler about 9 yearsThey got it so wrong. They should have restrict the min and max date format to invariant culture.
-
StackThis about 8 yearsHow do you use this? An example please?
-
MadHenchbot about 8 yearsIf your class name is MyDateAttribute, simply put [MyDate] above the property you want to restrict.
-
Bimal Das over 7 yearscan we make this dynamic ?? For example , [CustomDateRange(startDate=DateTime.Now,DateTime.Now.AddDays(5))]
-
ProfK about 7 years@BimalDas No. The ctors for the attribute must take compile time constants, but maybe you can try DI'ing the required values into the parameterless ctor for
MyDateAttribute
. -
ProfK about 7 yearsSorry, @BimalDas, I meant DI container resolving the required values in the parameterless ctor.
-
Admin over 6 yearsALthough you can make it work by configuring the
$.validator
- MVC model validation for date -
Richard almost 5 yearsI used this approach but as a GET request. You can implement it globally using the Request.QueryString[0] as the dob parameter instead of a strongly typed model. Discovered this to be more suitable to my project because I'm using complex models and I don't like dependency on the correct case/spelling of parameters.
-
Richard almost 5 yearsI could not get this to work for love nor money. I think it's possibly something to do with the date formats being entered by users and the date formats so I used [Remote] annotation for a custom controller to solve.
-
CoderSteve about 3 yearsShame that this isn't at the top of the page. Stack Overflow definitely lacks something.