0

How do I allow users to only enter an old date if I have this code in model, before the BirthDate property?

[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public System.DateTime BirthDate { get; set; }

Can this be achieved without using JavaScript? If yes, how?

b.g
  • 411
  • 1
  • 3
  • 19
  • What do you mean by old date? – Botonomous Oct 13 '16 at 13:26
  • you can use this http://stackoverflow.com/questions/17321948/is-there-a-rangeattribute-for-datetime – Emil Oct 13 '16 at 13:33
  • Do you mean if you have a property birthday and user enters a date i.e 11/12/1995. If user wants to edit the birthday they can enter any date less than 11/12/1995 i.e 10/12/1994? – dijam Oct 13 '16 at 13:56
  • Use a conditional validation attribute such as a [foolproof](http://foolproof.codeplex.com/) `[LessThan]` attribute (or write your own) –  Oct 13 '16 at 21:02
  • @StephenMuecke I wrote a custom validator for this one. However, user can still view a future date, i.e. calendar still shows future date. Is there a way to limit calendar to display dates between those specified range? – b.g Oct 14 '16 at 05:48
  • If your using a jquery datepicker plugin it will have options for setting the max date. If you using the browsers HTML-5 datepicker (which is only supported in Chrome and Edge), then you can use the `max="2016-10-14"` attribute –  Oct 14 '16 at 05:52

1 Answers1

0

You should extend the RangeAttribute to decorate DateTime models field.

You may for example create a new validation attribute: BirthDateAttribute

public class BirthDateAttribute : RangeAttribute {

   public BirthDateAttribute() 
                   : base(
                           typeof(DateTime), 
                           DateTime.Now.AddYears(-120).ToShortDateString(), 
                           DateTime.Now.AddDays(-1)ToShortDateString()
                     ) { } 
}

And then, you can apply it to decorate your DateTime property:

[BirthDateAttribute]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public System.DateTime BirthDate { get; set; }
Ciro Corvino
  • 2,038
  • 5
  • 20
  • 33
  • Where do I write this custom validator if i am using MVC with EF? – b.g Oct 14 '16 at 04:59
  • Everywhere, but I suggest you to write in the model folder a sub folder ValidationExtension and there add a class file BirthDateAttribute.cs.. using the same namespace of your model. Then decorate your model with the new attribute – Ciro Corvino Oct 14 '16 at 08:49