EmailAttribute 和必需的验证失败
EmailAttribute and Required Validation Fails
我在 Blazor 服务器应用程序中有一个带有 Email
属性 表单的模型:
class Inputs
{
[Required]
[EmailAddress]
public string Email { get; set; }
}
我也有这个助手class(上下文):
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]
,验证工作正常。
什么可能导致此处验证失败?
我忘记在剃须刀标记中向我的 <EditForm>
添加 DataAnnotationsValidator
:
<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
:
Adds Data Annotations validation support to an EditContext.
我在 Blazor 服务器应用程序中有一个带有 Email
属性 表单的模型:
class Inputs
{
[Required]
[EmailAddress]
public string Email { get; set; }
}
我也有这个助手class(上下文):
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]
,验证工作正常。
什么可能导致此处验证失败?
我忘记在剃须刀标记中向我的 <EditForm>
添加 DataAnnotationsValidator
:
<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
:
Adds Data Annotations validation support to an EditContext.