验证在 Blazor 服务器端不起作用

Pep*_*ger 5 c# asp.net asp.net-core blazor-server-side

我定义了一个LogInForm.cs这样的表格:

using System.ComponentModel.DataAnnotations;

namespace PollingInstitute.Data.LogIn
{
    public class LogInForm
    {
        [Required]
        [DataType(DataType.EmailAddress, ErrorMessage = "This field require a mail adress (example : abc@xyz.com)")]
        public string Mail { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

和这样的登录屏幕LogIn.razor

@page "/login"
@using PollingInstitute.Data.LogIn
@inject LogInService _LogInService

<h3>Login</h3>

<EditForm Model="@logInForm" OnValidSubmit="@TryLogIn">

    <div>
        <label>Mail Adress : </label><InputText @bind-Value="@logInForm.Mail"></InputText>
        <ValidationMessage For="@(()=>logInForm.Mail)"></ValidationMessage>
    </div>

    <div>
        <label>Password : </label><InputText @bind-Value="@logInForm.Password"></InputText>
        <ValidationMessage For="@(()=>logInForm.Password)"></ValidationMessage>
    </div>

    <div>

        @if (!IsDisabled)
        {
            <button type="submit">Submit</button>
        }
        else
        {
            <label>Please wait...</label>
        }
    </div>
    <ValidationSummary></ValidationSummary>
</EditForm>

@code {

    LogInForm logInForm = new LogInForm();
    protected bool IsDisabled { get; set; } = false;

    async void TryLogIn()
    {
        if (IsDisabled == true)
        {
            IsDisabled = true;
            StateHasChanged();
            bool result = (await _LogInService.TryLogIn(logInForm));
            Console.WriteLine("Logging status : " + (result ? "Sucess" : "Failure"));
            IsDisabled = false;
            StateHasChanged();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

当我填写(或不填写)字段时,它总是将它们指示为有效,即使它应该是无效的。

我检查了_Imports.razor,它得到了Microsoft.AspNetCore.Components.Forms图书馆。我尝试过 Chrome 和 Firefox,它总是给出相同的结果。我检查了javascript是否打开,它是。

那么我做错了什么?和我的代码有关系吗?我必须在Startup.cs文件中添加一些东西吗?我使用验证系统制作了一个 Blazor 应用程序作为教程,它运行完美。

tom*_*dox 6

我认为这里的问题只是您忘记添加实际执行验证的组件。要解决此问题,请在您的<EditForm Model="@logInForm" OnValidSubmit="@TryLogIn">行下方添加此行:

      <DataAnnotationsValidator />
Run Code Online (Sandbox Code Playgroud)

此外,该[DataType]属性用于格式化而不是验证。电子邮件地址的验证注释是[EmailAddress],因此也添加它,它应该按预期工作。更多关于这里

对此略有不妥;我来自 WinForms 世界,在那里验证通常感觉像是一个不可知的黑匣子。在 Blazor 中,它在文档代码中都有很好的记录,所以如果你想在任何时候了解更多关于它实际上是可能的。 Steve Sanderson 的这个博客在“Blazor 的表单和验证可扩展性”部分有一些非常好的大纲信息。