[英]Custom validation attribute is never validated
我正在嘗試創建一個自定義驗證屬性,以僅要求一個字段,具體取決於另一個字段的結果。
我遇到的問題是,從未調用過IsValid塊。 數據似乎正在進入領域,我已經能夠使用斷點進行檢查。
我嘗試將TryValidateModel(this)
放在OnPostAsync
並且可以通過斷點,但是我可以看到發生了另一個錯誤。
請求的操作對DynamicMethod無效
這是下面的代碼。 任何幫助,將不勝感激。
public class PageOneModel : PageModel
{
[BindProperty]
public bool CompanyHouseToggle { get; set; }
[BindProperty]
[StringLength(60, MinimumLength = 3)]
[RequiredIf("CompanyHouseToggle", desiredvalue: "true")]
public string CompanyNumber { get; set; }
[BindProperty]
[StringLength(60, MinimumLength = 3)]
public string OrganisationName { get; set; }
[BindProperty]
[RegularExpression(pattern: "(GB)?([0-9]{9}([0-9]{3})?|[A-Z]{2}[0-9]{3})", ErrorMessage = "This VAT number is not recognised")]
public string VatNumber { get; set; }
public void OnGet()
{
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
RedirectToPage("2");
}
}
public class RequiredIfAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
private String PropertyName { get; set; }
private Object DesiredValue { get; set; }
public RequiredIfAttribute(String propertyName, Object desiredvalue)
{
this.PropertyName = propertyName;
this.DesiredValue = desiredvalue;
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
var property = context.ObjectType.GetProperty(PropertyName);
if (property == null)
throw new ArgumentException("Property with this name not found");
// Just for testing purposes.
return new ValidationResult(ErrorMessage);
}
}
我建議您從ReuiredAttribute繼承。 它完全適合我。
public class RequiredUnlessDeletingAttribute : RequiredAttribute
{
string DeletingProperty;
/// <summary>
/// Check if the object is going to be deleted skip the validation.
/// </summary>
/// <param name="deletingProperty">The boolean property`s name which shows the object will be deleted.</param>
public RequiredUnlessDeletingAttribute(string deletingProperty = "MustBeDeleted") =>
DeletingProperty = deletingProperty;
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var property = validationContext.ObjectType.GetProperty(deletingProperty);
if ((bool)property.GetValue(validationContext.ObjectInstance))
return ValidationResult.Success;
return base.IsValid(value, validationContext);
}
}
在此處檢查完整的實施
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.