[英]How to Localize validation message (DataAnnotationsValidator) in blazor server side
[英]How can I verify that two fields match using DataAnnotationsValidator in Blazor?
我对开发相当陌生,并尝试使用 Blazor 学习 C# 开发。 我目前正在学习如何使用EditForms
构建 forms 并使用DataAnnotationsValidator
进行验证。
在继续处理表单之前,我已经成功完成了验证所需的大部分工作,但是,我在验证的一个重要方面遇到了麻烦:我正在处理的表单是新用户的注册表单. 通常,在注册新用户时,您可能希望让用户重新输入一个值,例如 email 地址或密码,以确保他们输入正确:
<InputText @bind-Value=User.email id="email" /><br />
<ValidationMessage For=@( () => User.email) />
<label for="confirm">Confirm Email</label><br />
<InputText @bind-Value=User.confirm id="confirm"/><br />
为了验证这些字段,我有 class UserModel,我已将其实例化为 User()。
@code
{
UserModel User = new UserModel();
class UserModel
{
[Required]
[EmailAddress(ErrorMessage = "Please enter a valid email address.")]
public string email { get; set; }
[Required]
[EmailAddress(ErrorMessage = "Please confirm your email address.")]
[Compare(email, ErrorMessage = "The email addresses you entered did not match.")]
public string confirm { get; set; }
public string fname { get; set; }
public string lname { get; set; }
public string pwd { get; set; }
public string error = "";
public void Submit()
{
}
}
在 Microsoft 的DataAnnotationsValidator
文档中,我发现了一个 Class CompareAttribute
,根据文档,它“提供了一个比较两个属性的属性”。 我相信这会满足我的需要,但我无法使用它。 Compare
接受参数otherProperty
,我认为该参数是我要匹配的其他用户输入,但是,我不知道如何将先前的输入作为此参数传递。
我试过email,
但是,需要 object 参考。 似乎我不想在 class 本身中引用 class 的实例,所以我尝试了这个this.email
但得到错误“关键字'this'在当前上下文中不可用”。
如果有人能帮我找出在我的情况下使用Compare
class 的正确方法,我将不胜感激。 否则,如果我叫错了树,请告诉我。 谢谢!
对于 Blazor 应用程序,Microsoft 创建了新的 NuGet package Microsoft.AspNetCore.Components.DataAnnotations.Validation以用于DataAnnotationsValidator组件。 此库在与以前的[Compare]
属性相同的命名空间中定义属性[CompareProperty]
,它是直接替换的。
工作示例:
@using System.ComponentModel.DataAnnotations;
<EditForm Model="@_user" OnValidSubmit="HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<label>
Email:
<InputText @bind-Value="_user.Email" />
</label>
<label>
Confirm:
<InputText @bind-Value="_user.ConfirmEmail" />
</label>
<button type="submit">Submit</button>
</EditForm>
@code {
private User _user = new User();
private void HandleValidSubmit()
{
Console.WriteLine("OnValidSubmit");
}
public class User
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[CompareProperty("Email")]
public string ConfirmEmail { get; set; }
}
}
您可以在文档中阅读更多关于为什么 Blazor 应用程序不需要使用[Compare]
属性的信息。
这篇文章 stackoverflow.com/a/13237249/842935 回答了我的问题(感谢 Dani Herrera 指出这一点)。
参数是一个字符串,它表示您要比较的属性的名称。 因此,以下代码将完成我想要完成的工作:
[Compare("email", ErrorMessage = "The email addresses you entered did not match.")]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.