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

我这样定义了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; }
    }
}

还有这样的登录屏幕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();
        }
    }

}

当我填写(或不填写)这些字段时,即使它被认为是无效的,也总是表明它们是有效的。

我检查了_Imports.razor,它得到了microsoft.AspNetCore.Components.Forms库。 我尝试过使用Chrome和Firefox,但始终能得到相同的结果。 我检查了javascript是否已启用。

那我做错了什么?我的代码有什么关系吗?是否需要在Startup.cs文件中添加一些内容?我使用验证系统制作了Blazor应用程序作为教程,并且运行正常。

ashinelee 回答:验证在Blazor服务器端不起作用

我认为这里的问题仅仅是因为您忘记添加实际的验证器组件。将此行添加到<EditForm Model="@logInForm" OnValidSubmit="@TryLogIn">行下面:

      <DataAnnotationsValidator />

此外,[DataType]属性用于格式设置而不是验证。电子邮件地址的验证批注是[EmailAddress],因此也要添加该批注,它应该可以正常工作。有关here的更多信息。

对此略有保留;我来自WinForms世界,那里的验证通常感觉就像是一个不可知的黑匣子。在Blazor中,in the docsin the code的文档都很好,因此,如果您想随时了解更多信息,实际上是有可能的。 This blog by Steve Sanderson在“ Blazor的表单和验证可扩展性”部分中提供了一些非常好的大纲信息。

本文链接:https://www.f2er.com/3095458.html

大家都在问