使用子组件时,Blazor EditForm 验证不起作用

Mat*_*ice 11 validation blazor

我有一个名为 EditOffice 的 Blazor 组件。它看起来如下:

<EditForm Model="@Office" OnValidSubmit="@HandleValidSubmit">

    <DataAnnotationsValidator />
    <ValidationSummary />

    <InputTextRow Label="Name" @bind-Value="@Office.Name" Placeholder="Enter name" />
    <InputTextRow Label="ABN" @bind-Value="@Office.ABN" Placeholder="Enter ABN" />
...
    <button type="submit" class="btn btn-primary edit-btn">Save office</button>
</EditForm>

Run Code Online (Sandbox Code Playgroud)

我创建了名为 InputTextRow 的子组件,试图整理我的代码。它们如下所示:

<div class="form-group row">
    <label for="@Id" class="col-sm-3">@Label: </label>
    <InputText id="@Id" @oninput="OnValueChanged" @bind-Value="@Value" class="form-control col-sm-8" placeholder="@Placeholder"></InputText>
    <ValidationMessage class="offset-sm-3 col-sm-8" For="@(() => Value)" />
</div>

@code {

    public string Id => Label.ToLower().Replace(" ", "");

    [Parameter]
    public string Label { get; set; }

    [Parameter]
    public string Value { get; set; }

    [Parameter]
    public string Placeholder { get; set; }

    [Parameter] public EventCallback<string> ValueChanged { get; set; }

    Task OnValueChanged(ChangeEventArgs e)
    {
        Value = e.Value.ToString();
        return ValueChanged.InvokeAsync(Value);
    }
}
Run Code Online (Sandbox Code Playgroud)

ValidationMessage 在我的子组件中不起作用。知道为什么吗?

Raf*_*ski 7

我知道我有点晚了,但这是我的答案:)

所以现在有更好的解决方案。

TL:懒人的DR解决方案

请注意 - 它是实验性的,但包已经在候选版本中,所以我猜不用担心。

使用Microsoft.AspNetCore.Components.DataAnnotations.Validation包,<ObjectGraphDataAnnotationsValidator />而不是<DataAnnotationsValidator />使用这个东西:

using System.ComponentModel.DataAnnotations;

public class YourComplexModel
{
    // other properties

    [ValidateComplexType] // <--life saver
    public ChildModel ChildModel { get; set; } = new ChildModel();
}
Run Code Online (Sandbox Code Playgroud)

来自 MS Docs 的片段

链接微软文档

Blazor 支持使用带有内置 DataAnnotationsValidator 的数据注释来验证表单输入。但是,DataAnnotationsValidator 只验证绑定到表单的模型的顶级属性,这些属性不是集合或复杂类型的属性。

要验证绑定模型的整个对象图,包括集合类型和复杂类型属性,请使用由实验性Microsoft.AspNetCore.Components.DataAnnotations.Validation包提供的 ObjectGraphDataAnnotationsValidator :

<EditForm Model="@model" OnValidSubmit="@HandleValidSubmit">
    <ObjectGraphDataAnnotationsValidator />
    ...
</EditForm>
Run Code Online (Sandbox Code Playgroud)

使用 [ValidateComplexType] 注释模型属性。在以下模型类中, ShipDescription 类包含额外的数据注释,用于在模型绑定到表单时进行验证:

Starship.cs:

using System;
using System.ComponentModel.DataAnnotations;

public class Starship
{
    ...

    [ValidateComplexType]
    public ShipDescription ShipDescription { get; set; } = 
        new ShipDescription();

    ...
}
Run Code Online (Sandbox Code Playgroud)

ShipDescription.cs:

using System;
using System.ComponentModel.DataAnnotations;

public class ShipDescription
{
    [Required]
    [StringLength(40, ErrorMessage = "Description too long (40 char).")]
    public string ShortDescription { get; set; }

    [Required]
    [StringLength(240, ErrorMessage = "Description too long (240 char).")]
    public string LongDescription { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

  • 今天这个不存在,目前还有其他有效的解决方案吗? (2认同)

小智 0

我有完全相同的问题。我的代码与你的非常相似。我的子组件确实进行了验证,但未显示验证错误消息。

我确实使用这个扩展方法:

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

namespace TimeRecording.Extensions
{
    public static class EditContextExtensions
    {
        static PropertyInfo IsModifiedProperty;
        static MethodInfo GetFieldStateMethod;

        /// <summary>
        /// Validates an entire object tree
        /// </summary>
        /// <param name="editContext">The EditContext to validate the Model of</param>
        /// <returns>True if valid, otherwise false</returns>
        public static bool ValidateObjectTree(this EditContext editContext)
        {
            var validatedObjects = new HashSet<object>();
            ValidateObject(editContext, editContext.Model, validatedObjects);
            editContext.NotifyValidationStateChanged();
            return !editContext.GetValidationMessages().Any();
        }

        public static void ValidateProperty(this EditContext editContext, FieldIdentifier fieldIdentifier)
        {
            if (fieldIdentifier.Model == null)
                return;

            var propertyInfo = fieldIdentifier.Model.GetType().GetProperty(
                fieldIdentifier.FieldName,
                BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static);

            var validatedObjects = new HashSet<object>();
            ValidateProperty(editContext, fieldIdentifier.Model, propertyInfo, validatedObjects);
        }

        private static void ValidateObject(
            EditContext editContext,
            object instance,
            HashSet<object> validatedObjects)
        {
            if (instance == null)
                return;

            if (validatedObjects.Contains(instance))
                return;

            if (instance is IEnumerable && !(instance is string))
            {
                foreach (object value in (IEnumerable)instance)
                    ValidateObject(editContext, value, validatedObjects);
                return;
            }

            if (instance.GetType().Assembly == typeof(string).Assembly)
                return;

            validatedObjects.Add(instance);

            var properties = instance.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            foreach (PropertyInfo property in properties)
                ValidateProperty(editContext, instance, property, validatedObjects);
        }

        private static void ValidateProperty(
            EditContext editContext,
            object instance,
            PropertyInfo property,
            HashSet<object> validatedObjects)
        {
            NotifyPropertyChanged(editContext, instance, property.Name);

            object value = property.GetValue(instance);
            ValidateObject(editContext, value, validatedObjects);
        }

        private static void NotifyPropertyChanged(
            EditContext editContext,
            object instance,
            string propertyName)
        {
            if (GetFieldStateMethod == null)
            {
                GetFieldStateMethod = editContext.GetType().GetMethod(
                    "GetFieldState",
                    BindingFlags.NonPublic | BindingFlags.Instance);
            }

            var fieldIdentifier = new FieldIdentifier(instance, propertyName);
            object fieldState = GetFieldStateMethod.Invoke(editContext, new object[] { fieldIdentifier, true });

            if (IsModifiedProperty == null)
            {
                IsModifiedProperty = fieldState.GetType().GetProperty(
                    "IsModified",
                    BindingFlags.Public | BindingFlags.Instance);
            }

            object originalIsModified = IsModifiedProperty.GetValue(fieldState);
            editContext.NotifyFieldChanged(fieldIdentifier);
            IsModifiedProperty.SetValue(fieldState, originalIsModified);
        }

    }
}
Run Code Online (Sandbox Code Playgroud)