【问题标题】:Business Validation with ObjectGraphDataAnnotationsValidator with complex type model使用具有复杂类型模型的 ObjectGraphDataAnnotationsValidator 进行业务验证
【发布时间】:2026-01-11 16:20:06
【问题描述】:

在我的 blazor 服务器应用程序中,我基于 this 完成了业务验证

   @page "/"
   @inherits IndexBase
   <EditForm Model="@MyModel" OnValidSubmit="@HandleValidSubmit">
    <ObjectGraphDataAnnotationsValidator />
    <CustomValidator @ref="customValidator" />
    <ValidationSummary />
      <div>
        <InputText @bind-Value="MyModel.Customer.Name"></InputText>
        <ValidationMessage For="()=>MyModel.Customer.Name" />
      </div>
      <div>
        <InputNumber @bind-Value="MyModel.Customer.Age"> </InputNumber>
        <ValidationMessage For="()=>MyModel.Customer.Age" />
      </div>
      <button Text="Save" type="submit">Get Result</button>
    </EditForm>

及其基类包含

    public class IndexBase:ComponentBase
     {
       protected MyModel MyModel { get; set; } = new MyModel();
       protected CustomValidator customValidator;
       protected void HandleValidSubmit()
        {
        customValidator.ClearErrors();
        var errors = new Dictionary<string, List<string>>();
        if ( MyModel.Customer.Name.ToLower().StartsWith("a"))
        {
            errors.Add("Customer.Age", new List<string>() { "Age should be greater than 10" });
        }
        if (errors.Count() > 0)
        {
            customValidator.DisplayErrors(errors);
        }
        else
        {
            // Process the form
        }
    }
}

MyModel 看起来像

     public class MyModel
      {
        [ValidateComplexType]
        public Customer Customer { get; set; } = new Customer();
      }

public class Customer
{
    [Required]
    public string Name { get; set; }
    public int Age { get; set; }0
}

我的 CustomValidator 看起来像下面的代码(来自here

         public class CustomValidator : ComponentBase
         {
          private ValidationMessageStore messageStore;

       [CascadingParameter]
       private EditContext CurrentEditContext { get; set; }

       protected override void OnInitialized()
       {
        if (CurrentEditContext == null)
        {
            throw new InvalidOperationException(
                $"{nameof(CustomValidator)} requires a cascading " +
                $"parameter of type {nameof(EditContext)}. " +
                $"For example, you can use {nameof(CustomValidator)} " +
                $"inside an {nameof(EditForm)}.");
        }

        messageStore = new ValidationMessageStore(CurrentEditContext);

        CurrentEditContext.OnValidationRequested += (s, e) =>
            messageStore.Clear();
        CurrentEditContext.OnFieldChanged += (s, e) =>
            messageStore.Clear(e.FieldIdentifier);
    }

    public void DisplayErrors(Dictionary<string, List<string>> errors)
    {
        foreach (var err in errors)
        {
            FieldIdentifier x = CurrentEditContext.Field(err.Key);
            messageStore.Add(x, err.Value);
        }

        CurrentEditContext.NotifyValidationStateChanged();
    }

    public void ClearErrors()
    {
        messageStore.Clear();
        CurrentEditContext.NotifyValidationStateChanged();
    }
}

当我点击提交按钮验证代码有效,但不添加 修改无效 类到输入控件。所以这不会显示错误消息和红色边框来控制

【问题讨论】:

    标签: blazor-server-side blazor-client-side asp.net-blazor


    【解决方案1】:

    我可以这样做..

    protected void HandleValidSubmit()
    {
        customValidator.ClearErrors();
        var errors = new Dictionary<FieldIdentifier, List<string>>();
        if ( MyModel.Customer.Name.ToLower().StartsWith("a"))
        {
            errors.Add(new FieldIdentifier(MyModel.Customer, "Name"), new 
            List<string> { "Age should be greater than 10" });
        }
        if (errors.Count() > 0)
        {
            customValidator.DisplayErrors(errors);
        }
        else
        {
            // Process the form
        }
    }
    

    并像这样更改DisplayErrors方法中的参数类型,

    public void DisplayErrors(Dictionary<FieldIdentifier, List<string>> errors)
    {
        foreach (var err in errors)
        {
            messageStore.Add(err.Key, err.Value);
        }
        CurrentEditContext.NotifyValidationStateChanged();
    }
    

    【讨论】: