C#属性来检查一个日期是否比其他早期 [英] C# attribute to check whether one date is earlier than the other
本文介绍了C#属性来检查一个日期是否比其他早期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个视图模型包含两个日期时间的属性我MVC4 Prject:
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; }
有没有用C#一个简单的方法属性为 [比较(someProperty)]
来查看天气RentDate属性的值大于ReturnDate的货值?
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?
推荐答案
下面是一个非常快的基本实现(没有错误检查等)应该做你的要求(仅适用于服务器端...它不会做ASP .NET客户端的JavaScript验证)。我没有测试它,但应该足以让你开始。
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.
using System;
using System.ComponentModel.DataAnnotations;
namespace Test
{
[AttributeUsage(AttributeTargets.Property)]
public class DateGreaterThanAttribute : ValidationAttribute
{
public DateGreaterThanAttribute(string dateToCompareToFieldName)
{
DateToCompareToFieldName = dateToCompareToFieldName;
}
private string DateToCompareToFieldName { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
DateTime earlierDate = (DateTime)value;
DateTime laterDate = (DateTime)validationContext.ObjectType.GetProperty(DateToCompareToFieldName).GetValue(validationContext.ObjectInstance, null);
if (laterDate > earlierDate)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("Date is not later");
}
}
}
public class TestClass
{
[DateGreaterThan("ReturnDate")]
public DateTime RentDate { get; set; }
public DateTime ReturnDate { get; set; }
}
}
这篇关于C#属性来检查一个日期是否比其他早期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文