2016-07-29 32 views
1

我確實有一個實體類,具有一些必要的屬性,具體取決於選擇器。ASP.NET MVC。如何根據參數禁用所需的驗證?

例如:選擇器可以採用「1」或「2」。如果選擇器爲「1」,則需要一組參數。如果選擇器是「2」,則需要另一組參數。

class MyClass{ 

    public int Selector {get;set;} // 1 or 2 

    public string A_required_for_1 {get;set;} 
    public string B_required_for_1 {get;set;} 

    public string C_required_for_2 {get;set;} 
    public string D_required_for_2 {get;set;} 

    public string E_Required_for_both_selectors {get;set;} 

} 

用戶應該能夠在視圖中創建或編輯操作期間在選擇器之間切換。

客戶端驗證已經解決。

如何在服務器驗證中處理它?

+0

這是‘在某些情況下禁用需要確認屬性’不是複製 –

+1

請你幫個忙和獨立的編輯和你的應用程序中創建功能。 – Programmer

+0

@NicholasKinney我不明白你爲什麼評論適用於這個問題。你能澄清一下嗎? –

回答

2

您可以創建自己的自定義驗證屬性或使用MVC Foolproof Validation然後執行:

class MyClass 
{ 

    public int Selector {get;set;} // 1 or 2 

    [RequiredIf("Selector == 1", ErrorMessage = "Your Error Message")] 
    public string A_required_for_1 {get;set;} 

    [RequiredIf("Selector == 1", ErrorMessage = "Your Error Message")] 
    public string B_required_for_1 {get;set;} 

    [RequiredIf("Selector == 2", ErrorMessage = "Your Error Message")] 
    public string C_required_for_2 {get;set;} 

    [RequiredIf("Selector == 2", ErrorMessage = "Your Error Message")] 
    public string D_required_for_2 {get;set;} 

    [Required("Your Error Message")] 
    public string E_Required_for_both_selectors {get;set;} 

} 

似乎正如贏提到不一直在積極發展了一段時間,所以你可能會想要去沿着創建自己的自定義驗證屬性的路線,這需要更多的工作,但您可以更好地控制驗證本身。根據您的需要選擇。

對於一個自定義的驗證屬性,你可以做這樣的事情:

public class RequiredIfOtherProperty : ValidationAttribute 
{ 
    private readonly string _otherPropertyName; 
    private readonly string _compareValue; 

    public RequiredIfOtherProperty(string otherPropertyName, string compareValue) 
    { 
     _otherPropertyName = otherPropertyName; 
     _compareValue = compareValue; 
    } 

    protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
    { 
     var otherProperty = validationContext.ObjectType.GetProperty(_otherPropertyName); 
     if (otherProperty == null) 
     { 
      return new ValidationResult($"Property '{_otherPropertyName}' does not exist"); 
     ); 
    } 

    var otherPropertyValue = otherProperty.GetValue(validationContext.ObjectInstance, null); 
    if (!_compareValue.Equals(otherPropertyValue)) 
    { 
     return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName)); 
    } 

    return null; 
} 

應該給你,你可以做一個粗略的想法,你可以改變實際的驗證,但是你喜歡。然後,您可以像使用普通屬性一樣使用它。

[RequiredIfOtherProperty("SomeProperty", "ValueToCompareWith")] 
+1

不錯的圖書館,但它是***貝塔*** 0.9。 4517,並且自2012年5月14日起未更新。 – Win

+0

不錯的建議@Win –

+0

「自定義驗證屬性」是什麼意思? –

1

我相信mvcfoolproof會適合這種情況[https://foolproof.codeplex.com/][1] 它也可以在nuget上找到。它增加了額外的驗證屬性,如

[RequiredIf] 
[RequiredIfNot] 
[RequiredIfTrue] 
[RequiredIfFalse] 
[RequiredIfEmpty] 
[RequiredIfNotEmpty] 
[RequiredIfRegExMatch] 
[RequiredIfNotRegExMatch] 

這是非常簡單的使用。

+1

不錯的圖書館,但它是***貝塔*** 0.9.4517,並且自2012年5月14日以來一直未更新。 – Win

+0

不錯的建議@Win –