2012-10-08 34 views
1

我正在開發一個內容開發場景,實體很可能會以不完整的狀態創建,並且在一段時間內仍然不完整。涉及的工作流程非常特殊,阻止我使用更加結構化的DDD方法。ASP.NET MVC中的兩階段驗證

我有一套必須始終滿足的驗證規則,以及在實體「完成」之前必須滿足的另一組驗證規則。

我已經在使用內置的ASP.NET MVC驗證來驗證前者。我可以用什麼方法來捕捉後者?

例如: -

public class Foo 
{ 
    public int Id { get; set; } 

    public virtual ICollection<Bar> Bars { get; set; } 
} 

public class Bar 
{ 
    public int Id { get; set; } 

    [Required] // A Bar must be owned by a Foo at all times 
    public int FooId { get; set; } 
    public virtual Foo Foo { get; set; } 

    [Required] // A Bar must have a working title at all times 
    public string WorkingTitle { get; set; } 

    public bool IsComplete { get; set; } 

    // Cannot use RequiredAttribute on Description as the 
    // entity is very likely to be created without one, 
    // however a Description is required before the entity 
    // can be marked as "IsComplete" 
    public string Description { get; set; } 
} 

回答

1

有不同的方法,你可以使用:

  • 有你的模型實現IValidatableObject接口,並且不使用數據標註執行條件的驗證。
  • 編寫一個自定義驗證屬性,該屬性將根據IsComplete屬性的值執行Description屬性的條件驗證邏輯。
  • 使用Mvc Foolproof已經爲您定義了RequiredIf驗證屬性,因此您無需自己編寫驗證屬性。
  • 使用FluentValidation.NET它允許您以流暢的方式表達您的驗證規則。使用這個庫編寫條件驗證規則不僅優雅,而且非常容易。它integrates nicely with ASP.NET MVC,也可以讓你輕鬆地隔離unit test your validation logic

就我個人而言,我會去FV.NET,但如果它更適合您的需求,您可以使用任何其他方法。

+0

嘎!基於「IsComplete」字段的值進行條件驗證。我爲什麼沒有想到這一點! /捂臉。 –