2010-05-18 113 views
1

如何通过验证应用程序块验证DateTime,以使其不超过DateTime.Now?在验证应用程序块中验证DateTime

谢谢。

+0

我想为DateOfBirth field.so使用验证程序,因此我不想接受大于系统日期的日期。我如何检查? – Wilson 2010-05-18 11:37:53

回答

0

您可以使用正则表达式进行验证只是选择时间格式http://regexlib.com/REDetails.aspx?regexp_id=504

+0

问题是关于作为企业库一部分的验证应用程序块。 – Vadim 2010-05-18 12:50:09

+0

@Vadim我看到了,但它更容易与正则表达式 – Xenon 2010-05-18 13:33:18

+0

问题不在于格式...它是关于有一个DateTime值小于或等于另一个DateTime值。 – 2010-05-19 16:07:12

0

我想做到这一点使用的验证应用程序块将创建一个返回DateTime.Now属性,然后使用性能对比验证的最简单方法。

SelfValidation还可以让你做你想做的。 Property Comparison Validator允许您将逻辑外部化,但仅仅为了比较而暴露属性感觉有点不对。

实施

public class Person 
{ 
    public DateTime Now 
    { 
     get { return DateTime.Now; } 
    } 

    public DateTime BirthDate 
    { 
     get; 
     set; 
    } 
} 


<type assemblyName="MyApp.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="MyApp.Entities.Person"> 
    <ruleset name="MyRuleSet"> 
    <properties> 
     <property name="BirthDate"> 
     <validator operator="LessThanEqual" propertyToCompare="Now" negated="false" 
      messageTemplate="I don't know nothin' about birthin' no babies in the future." messageTemplateResourceName="" 
      messageTemplateResourceType="" tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.PropertyComparisonValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=4.1.0.0, Culture=neutral, PublicKeyToken=null" 
      name="Property Comparison Validator" /> 
     </property> 
    </properties> 
    </ruleset> 
</type> 
0

可以使用RelativeDateTimeValidator。下面假设我们没有140岁以上的人(worlds oldest,到目前为止,在死亡时是122)。

[RelativeDateTimeValidator(-140, DateTimeUnit.Years, 0, DateTimeUnit.Second, 
     MessageTemplate = "Sorry, no predicted births allowed.")] 
public DateTime DateOfBirth 
{ get; set;}