【问题标题】:Validate DateTime in Validation Application Block在验证应用程序块中验证日期时间
【发布时间】:2010-05-18 11:17:29
【问题描述】:

如何通过Validation Application Block来验证DateTime,不超过DateTime.Now?

谢谢。

【问题讨论】:

  • 我想对 DateOfBirth 字段使用验证器。所以我不想接受大于系统日期的日期。我该如何检查?

标签: .net validation enterprise-library


【解决方案1】:

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

【讨论】:

  • 问题是关于作为企业库一部分的验证应用程序块。
  • @Vadim 我明白了,但使用正则表达式更容易
  • 问题不在于格式...而是关于 DateTime 值小于或等于另一个 DateTime 值。
【解决方案2】:

我认为使用验证应用程序块执行此操作的最简单方法是创建一个返回 DateTime.Now 的属性,然后使用属性比较验证器。

SelfValidation 还可以让你做你想做的事。属性比较验证器可让您将逻辑外部化,但公开一个属性只是为了进行比较感觉有点不对。

实施

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>

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      • 2015-07-18
      • 1970-01-01
      • 2011-12-28
      • 1970-01-01
      相关资源
      最近更新 更多