c# - EmailAttribute 和必需的验证失败
问题描述
我有一个模型,其中Email
包含 Blazor 服务器应用程序中表单的属性:
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]
在应用程序的其他地方使用过,并且验证按预期工作。
什么可能导致验证失败?
解决方案
DataAnnotationsValidator
我忘了<EditForm>
在剃刀标记中添加一个:
<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 添加数据注释验证支持。
推荐阅读
- xcode - 找不到有效版本的 XCode
- java - Netbeans Ide ')' 预期
- hyperledger-fabric - 限制在超级账本结构中再次输入相同的关键数据
- php - 如何在php中查找错误
- swift4 - 哪个最好为 UIButton 提供 shadowColor、Radius、Opacity 和cornerRadius?按钮扩展或 IBDesignable?
- ms-access - MS Access - 在表单之间传递登录信息
- c# - 如何在 Windows 窗体应用程序 C# 中检索 Google 联系人?
- database - 如何每天存储和索引数十亿条日志
- amazon-web-services - Kinesis Firehose 数据传输延迟
- gradle - Doop:Gradle 构建失败并出现异常。无法解决依赖关系