如何在 EditForm 中使用的组件中实现自定义业务逻辑验证

How to implement custom business logic validation in a component used in EditForm

我有一个显示多个“MyCustomComponents”的 EditForm

每个自定义组件实现自己的业务逻辑验证,在 EditForm 中调用 HandleValidSubmit() 时必须检查这一点。应该怎么做?

我正在使用 https://docs.microsoft.com/en-us/aspnet/core/blazor/forms-validation?view=aspnetcore-6.0#validator-components:

using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;

namespace MyNamespace
{
    // From https://docs.microsoft.com/en-us/aspnet/core/blazor/forms-validation?view=aspnetcore-6.0#validator-components
    public class CustomValidation : ComponentBase
    {
        private ValidationMessageStore? messageStore;

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

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

            messageStore = new(CurrentEditContext);

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

        public void DisplayErrors(Dictionary<string, List<string>> errors)
        {
            if (CurrentEditContext is not null)
            {
                foreach (var err in errors)
                {
                    messageStore?.Add(CurrentEditContext.Field(err.Key), err.Value);
                }

                CurrentEditContext.NotifyValidationStateChanged();
            }
        }

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

然后在我的编辑表单中:

<EditForm EditContext="@_editContext" OnValidSubmit="HandleValidSubmit" @onreset="HandleReset">
  <MyCustomComponent1/>
  <MyCustomComponent2/>
</EditForm>

并且在我使用的每个自定义控件中:

<CustomValidation @ref="customValidation"/>
<ValidationSummary/>

然后在每个组件中实现业务逻辑验证,例如:

        private bool Validate ()
        {
            customValidation?.ClearErrors();

            var errors = new Dictionary<string, List<string>>();

           // Add any validation errors
           errors.Add(nameof(Item), new() { "Item is required." });

            if (errors.Any())
            {
                customValidation?.DisplayErrors(errors);
                return false;
            }

            return true;
        }

但是如何从托管页面的 EditForm 中的 HandleValidSubmit 调用每个组件的验证?

您的组件应该订阅 EditContext.OnValidationRequested,您将把它作为级联参数。不要忘记实施 IDisposable 和取消订阅。