首页 > 解决方案 > EmailAttribute 和必需的验证失败

问题描述

我有一个模型,其中Email包含 Blazor 服务器应用程序中表单的属性:

class Inputs
{
    [Required]
    [EmailAddress]
    public string Email { get; set; }
}

我也有这个助手类(用于上下文):

public class FormModel<T> where T : class, new()
{
    private readonly EditContext EditContext;

    public FormModel()
    {
        Model = new T();
        EditContext = new EditContext(Model);
    }

    public T Model
    {
        get;
        init;
    }

    public EditContext Validation => EditContext;
}

当我对值运行验证时"admin",我会返回true而不是false

private readonly FormModel<Inputs> Form = new(); 

private void Submit() {
    // Debugger: Form.Model.Email = "admin"
    bool isValid = Form.Validation.Validate(); // true - not what I expect for "admin"
    if (!isValid) {
        return;
    }
    // ... code that should not be currently hit, but is ...
}

我运行时的调试器:
调试器 2

Email根本没有提供时也会发生同样的事情(尽管我不确定是否[Required]将空字符串视为非答案?):
调试器 1

我已经[EmailAddress]在应用程序的其他地方使用过,并且验证按预期工作。
像我期望的那样工作

什么可能导致验证失败?

标签: c#.netrazorblazor.net-5

解决方案


DataAnnotationsValidator我忘了<EditForm>在剃刀标记中添加一个:

<EditForm EditContext="@Form.Validation" OnValidSubmit="Submit">

    <DataAnnotationsValidator /> @* <-- was missing this *@

    <InputText @bind-Value="@Form.Model.Email"
                class="standard-input"
                type="email"
                placeholder="Email" />
    <ValidationMessage For="@(() => Form.Model.Email)" />
    ...
</EditForm>

这是必要的,因为DataAnnotationsValidator

向 EditContext 添加数据注释验证支持。


推荐阅读