0

I have an EditForm displaying a number of "MyCustomComponents"

Each custom component implements its own business logic validation, this must be checked when HandleValidSubmit() is called in the EditForm. How should this be done?

I'm using from https://learn.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://learn.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();
        }
    }
}

Then in my edit form:

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

And in each of my custom controls I use:

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

Then implement the business logic validation in each component, e.g.:

        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;
        }

But how can I call Validate on each component from the HandleValidSubmit in the EditForm of the hosting page?

1 Answer 1

1

Your component should subscribe to EditContext.OnValidationRequested, which you will have as a cascading parameter. Don't forget to implement IDisposable and unsubscribe.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.