【问题标题】:EmailAttribute and Required Validation FailsEmailAttribute 和必需的验证失败
【发布时间】:2021-06-02 09:17:58
【问题描述】:

我在 Blazor 服务器应用程序中有一个带有 Email 属性的模型:

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

我运行时的调试器:

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

我在应用程序的其他地方使用了[EmailAddress],验证按预期工作。

什么可能导致验证失败?

【问题讨论】:

    标签: c# .net razor blazor .net-5


    【解决方案1】:

    我忘记在剃刀标记中将DataAnnotationsValidator 添加到我的&lt;EditForm&gt;

    <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 添加数据注释验证支持。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      • 2016-10-03
      • 2018-11-15
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多