2010-05-18 109 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;}