2012-03-14 62 views
2

考慮下面的代碼:驗證複雜的類在MVC

public class AccountNumber 
{ 
    [AccountNumber] //This validator confirms the format of the account number 
    public string Value {get; set;} 

    public int Format { get; set;} 

    public string ToString() 
    { 
     return Value + " is format " + Format; 
    } 
} 

public class MyViewModel 
{ 
    public MyViewModel() 
    { 
      SourceAccount = new AccountNumber(); 
      DestinationAccount= new AccountNumber(); 
    } 

    [Required] 
    AccountNumber SourceAccount {get; set;} 

    AccountNumber DestinationAccount {get; set;} 
} 

然後,在我看來:

@Html.EditorFor(model => model.SourceAccount.Value) 
@Html.EditorFor(model => model.DestinationAccount.Value) 

基本上,我想說的是,用戶必須輸入源科目,並且他們可選地輸入目的地賬戶。但是,如果他們輸入了目的地賬戶,則其必須符合某種格式。

上述代碼的問題是,SourceAccount上的必需驗證器將始終返回有效值,因爲SourceAccount永遠不會爲null。什麼是一個很好的方法來實現我想要實現的目標?

請注意,在現實生活中,Value的設置程序比顯示的更復雜,因爲它會以規範格式重新格式化帳戶號碼。

編輯請注意,我們必須使用內置的MVC驗證,因爲這是該項目目前使用的其餘部分。

回答

0

也許您想嘗試FluentValidation,它是數據註記屬性的替代模型,它允許您添加更復雜的模型驗證邏輯。

的代碼仍然是相當簡潔明瞭:

[Validator(typeof(PersonValidator))] 
public class Person 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string Email { get; set; } 
    public int Age { get; set; } 
} 

public class PersonValidator : AbstractValidator<Person> 
{ 
    public PersonValidator() 
    { 
     RuleFor(x => x.Id).NotNull(); 
     RuleFor(x => x.Name).Length(0, 10); 
     RuleFor(x => x.Email).EmailAddress(); 
     RuleFor(x => x.Age).InclusiveBetween(18, 60); 
    } 
} 
+0

感謝您的建議尼科。不幸的是,我們必須使用MVC驗證,因爲項目目前正在使用該驗證。我現在已經在這個問題上明確表達了。 – 2012-03-14 15:08:00

1

一個簡單的方法可能是爲SourceAccount和DestinationAccount號添加簡單的字符串屬性如下:

public class MyViewModel 
{ 
    public MyViewModel() 
    { 
    } 

    [Required] 
    [AccountNumber] 
    public string SourceAccountNumber { get; set; } 

    [AccountNumber] 
    public string DestinationAccountNumber { get; set; } 

    public AccountNumber SourceAccount 
    { 
     get 
     { 
      return new AccountNumber 
      { 
       Value = SourceAccountNumber, 
       Format = 0 // Set Format appropriately 
      }; 
     } 
    } 

    public AccountNumber DestinationAccount 
    { 
     get 
     { 
      return new AccountNumber 
      { 
       Value = DestinationAccountNumber, 
       Format = 0 // Set Format appropriately 
      }; 
     } 
    } 
}