【问题标题】:Is it possible to check if Blazor ValidationMessageStore has ANY error message是否可以检查 Blazor ValidationMessageStore 是否有任何错误消息
【发布时间】:2021-12-03 19:44:18
【问题描述】:

我根据此模式使用 ValidationMessageStore 验证我的 Blazor 表单输入:

https://docs.microsoft.com/en-us/aspnet/core/blazor/forms-validation?view=aspnetcore-5.0#basic-validation-1

然后我在每个控件上输出 ValidationMessage。

但它是一个长表单,所以我还想在提交按钮附近的某个地方向用户表明存在一些需要修复的错误,这就是我们尚未接受输入的原因。

我知道我可以使用 ValidationSummary,但我不想重复所有可能的错误,只是记一下。

ValidationMessageStore 显然将所有消息保存在内部集合中,但它们不可访问。是否有可能以某种方式检查是否有任何错误消息?

【问题讨论】:

    标签: validation blazor


    【解决方案1】:

    查看ValidationSummary 代码 - 验证消息存储可用。它不是很复杂,因此您应该能够自己构建一个类似但更简单的组件来显示您想要的内容。

    代码在这里:https://github.com/dotnet/aspnetcore/blob/main/src/Components/Web/src/Forms/ValidationSummary.cs

    // Licensed to the .NET Foundation under one or more agreements.
    // The .NET Foundation licenses this file to you under the MIT license.
    
    using System;
    using System.Collections.Generic;
    using Microsoft.AspNetCore.Components.Rendering;
    
    namespace Microsoft.AspNetCore.Components.Forms
    {
        // Note: there's no reason why developers strictly need to use this. It's equally valid to
        // put a @foreach(var message in context.GetValidationMessages()) { ... } inside a form.
        // This component is for convenience only, plus it implements a few small perf optimizations.
    
        /// <summary>
        /// Displays a list of validation messages from a cascaded <see cref="EditContext"/>.
        /// </summary>
        public class ValidationSummary : ComponentBase, IDisposable
        {
            private EditContext? _previousEditContext;
            private readonly EventHandler<ValidationStateChangedEventArgs> _validationStateChangedHandler;
    
            /// <summary>
            /// Gets or sets the model to produce the list of validation messages for.
            /// When specified, this lists all errors that are associated with the model instance.
            /// </summary>
            [Parameter] public object? Model { get; set; }
    
            /// <summary>
            /// Gets or sets a collection of additional attributes that will be applied to the created <c>ul</c> element.
            /// </summary>
            [Parameter(CaptureUnmatchedValues = true)] public IReadOnlyDictionary<string, object>? AdditionalAttributes { get; set; }
    
            [CascadingParameter] EditContext CurrentEditContext { get; set; } = default!;
    
            /// <summary>`
            /// Constructs an instance of <see cref="ValidationSummary"/>.
            /// </summary>
            public ValidationSummary()
            {
                _validationStateChangedHandler = (sender, eventArgs) => StateHasChanged();
            }
    
            /// <inheritdoc />
            protected override void OnParametersSet()
            {
                if (CurrentEditContext == null)
                {
                    throw new InvalidOperationException($"{nameof(ValidationSummary)} requires a cascading parameter " +
                        $"of type {nameof(EditContext)}. For example, you can use {nameof(ValidationSummary)} inside " +
                        $"an {nameof(EditForm)}.");
                }
    
                if (CurrentEditContext != _previousEditContext)
                {
                    DetachValidationStateChangedListener();
                    CurrentEditContext.OnValidationStateChanged += _validationStateChangedHandler;
                    _previousEditContext = CurrentEditContext;
                }
            }
    
            /// <inheritdoc />
            protected override void BuildRenderTree(RenderTreeBuilder builder)
            {
                // As an optimization, only evaluate the messages enumerable once, and
                // only produce the enclosing <ul> if there's at least one message
                var validationMessages = Model is null ?
                    CurrentEditContext.GetValidationMessages() :
                    CurrentEditContext.GetValidationMessages(new FieldIdentifier(Model, string.Empty));
    
                var first = true;
                foreach (var error in validationMessages)
                {
                    if (first)
                    {
                        first = false;
    
                        builder.OpenElement(0, "ul");
                        builder.AddMultipleAttributes(1, AdditionalAttributes);
                        builder.AddAttribute(2, "class", "validation-errors");
                    }
    
                    builder.OpenElement(3, "li");
                    builder.AddAttribute(4, "class", "validation-message");
                    builder.AddContent(5, error);
                    builder.CloseElement();
                }
    
                if (!first)
                {
                    // We have at least one validation message.
                    builder.CloseElement();
                }
            }
    
            /// <inheritdoc/>
            protected virtual void Dispose(bool disposing)
            {
            }
    
            void IDisposable.Dispose()
            {
                DetachValidationStateChangedListener();
                Dispose(disposing: true);
            }
    
            private void DetachValidationStateChangedListener()
            {
                if (_previousEditContext != null)
                {
                    _previousEditContext.OnValidationStateChanged -= _validationStateChangedHandler;
                }
            }
        }
    }
    

    如果您在构建组件时需要更多帮助,请在问题中添加更多详细信息。

    【讨论】:

      【解决方案2】:

      我为我的问题找到了一个更简单的解决方案。在EditContext上找到了一个叫GetValidationMessages的方法。

      @if (editContext.GetValidationMessages().Any())
      {
          <div class="alert alert-danger">
              Some input was incomplete. Please review detailed messages above.
          </div>
      }
      

      【讨论】:

        猜你喜欢
        • 2021-09-26
        • 2012-09-07
        • 1970-01-01
        • 2018-09-12
        • 2019-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-18
        相关资源
        最近更新 更多