您可以創建自己的自定義驗證屬性或使用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")]
這是‘在某些情況下禁用需要確認屬性’不是複製 –
請你幫個忙和獨立的編輯和你的應用程序中創建功能。 – Programmer
@NicholasKinney我不明白你爲什麼評論適用於這個問題。你能澄清一下嗎? –