[英]Validation doesn't work on 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; }
}
}
还有一个登录屏幕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 应用程序作为教程,它运行良好。
我认为这里的问题只是您忘记添加实际执行验证的组件。 要解决此问题,请将此行添加到您的<EditForm Model="@logInForm" OnValidSubmit="@TryLogIn">
行下方:
<DataAnnotationsValidator />
此外, [DataType]
属性用于格式化而不是验证。 email 地址的验证注释是[EmailAddress]
,所以也添加它,它应该可以按预期工作。 更多关于这里。
顺便说一句; 我来自 WinForms 世界,在这个世界里,验证常常感觉像是一个不可知的黑匣子。 在 Blazor 中,它在文档和代码中都有很好的记录,所以如果你想在任何时候了解更多关于它的信息,它实际上是可能的。 Steve Sanderson 的这篇博客在“Blazor 的 forms 和验证可扩展性”部分中有一些非常好的大纲信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.