[英]How to use mvc dataannotations to validate property value if other property is set to true?
我正在嘗試驗證表單提交,但僅當另一個屬性設置為true時,我才想驗證一個屬性。
我的兩個屬性:
[DisplayName(Translations.Education.IsFeaturette)]
public bool IsFeaturette { get; set; }
[DisplayName(Translations.Education.AddFeaturetteFor)]
[CusomValidatorForFeaturettes(IsFeaturette)]
public string[] Featurettes { get; set; }
自定義注釋:
public class CusomValidatorForFeaturettes: ValidationAttribute
{
private readonly bool _IsFeatturette;
public CusomValidatorForFeaturettes(bool isFeatturette): base("NOT OK")
{
_IsFeatturette = isFeatturette;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null && _IsFeatturette )
{
var errorMessage = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(errorMessage);
}
return ValidationResult.Success;
}
}
基本上,如果isfeature為true,則Featurette必須具有價值!
錯誤即時消息:
非靜態字段,方法或屬性'EducationViewModel.IsFeaturette'需要對象引用
我不能將此屬性設置為靜態cuz,這會給我帶來麻煩,因為此屬性是通過enityframework設置的,並且我不希望更改任何屬性。 如何在不使屬性為靜態的情況下完成此操作?
屬性是在編譯時添加到程序集的元數據的,因此必須在編譯時知道其參數。 由於將屬性值( bool IsFeaturette
)傳遞給非靜態屬性(在運行時可能為true
或false
,因此會產生false
。
而是傳遞一個指示要比較的屬性名稱的字符串,然后在該方法中,使用反射來獲取屬性的值。
public bool IsFeaturette { get; set; }
[CusomValidatorForFeaturettes("IsFeaturette")]
public string[] Featurettes { get; set; }
並將驗證屬性修改為
public class CusomValidatorForFeaturettes: ValidationAttribute
{
private readonly string _OtherProperty;
public CusomValidatorForFeaturettes(string otherProperty): base("NOT OK")
{
_OtherProperty = otherProperty;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// Get the dependent property
var otherProperty = validationContext.ObjectInstance.GetType().GetProperty(_OtherProperty);
// Get the value of the dependent property
var otherPropertyValue = otherProperty.GetValue(validationContext.ObjectInstance, null);
......
然后,您可以將otherPropertyValue
轉換為bool
並進行條件檢查。
我還建議您閱讀ASP.NET-MVC-3第2部分中的《驗證的完整指南》,以更好地了解如何實現驗證屬性,包括如何實現IClientValidatable
以便同時獲得服務器端和客戶端驗證。 我還建議您將方法重命名為(例如) RequiredIfTrueAttribute
以更好地反映其作用。
還要注意, 萬無一失具有在MVC中使用的大量驗證屬性。
最后一點,當前的實現特定於對一個屬性( IsFeaturette
的值)的IsFeaturette
,這對驗證屬性毫無意義-您最好檢查一下控制器中的值並添加ModelStateError
。 上面的代碼意味着您可以傳入任何屬性名稱(只要該屬性為typeof bool
),這就是驗證屬性應允許的名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.