I have a ViewModel for my MVC4 Prject containing two DateTime properties:
[Required]
[DataType(DataType.Date)]
public DateTime RentDate { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime ReturnDate { get; set; }
Is there a simple way to use C# attributes as [Compare("someProperty")]
to check weather the value of RentDate property is earlier than the value of ReturnDate?
If you're using .Net Framework 3.0 or higher you could do it as a class extension...
Here is a very quick basic implementation (without error checking etc.) that should do what you ask (only on server side...it will not do asp.net client side javascript validation). I haven't tested it, but should be enough to get you started.
Nothing like that exists in the framework. A common similar attribute is the
RequiredIf
. It is described in this post.RequiredIf Conditional Validation Attribute
Not sure of it's use in MVC/Razor, but..
You can use DateTime.Compare(t1, t2) - t1 and t2 being the times you want to compare. It will return either -1, 0 or 1 depending on what the results are.
Read more here: http://msdn.microsoft.com/en-us/library/system.datetime.compare.aspx
Model:
Attribute class:
It looks like you're using DataAnnotations so another alternative is to implement
IValidatableObject
in the view model: