如何使用 Blazor 中的 DataAnnotationsValidator 验证两个字段是否匹配?

Raz*_*ick 6 c# asp.net-core blazor

我对开发相当陌生,并尝试使用 Blazor 学习 C# 开发。我目前正在学习如何使用 构建表单EditForms并使用 进行验证DataAnnotationsValidator。

在继续处理表单之前,我已经成功完成了验证所需的大部分工作,但是,我在验证的一个重要方面遇到了麻烦:我正在处理的表单是新用户的注册表单。通常,在注册新用户时,您可能希望让用户重新输入电子邮件地址或密码等值,以确保他们输入正确:

    <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 />
Run Code Online (Sandbox Code Playgroud)

为了验证这些字段,我有类 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()
        {
        }
    }
Run Code Online (Sandbox Code Playgroud)

在 Microsoft 的文档中DataAnnotationsValidator,我找到了一个 Class CompareAttribute,根据文档,它“提供了一个比较两个属性的属性”。我相信这可以满足我的需要,但我在使用它时遇到了困难。Compare接受otherProperty我认为将是我试图匹配的其他用户输入的参数,但是,我不知道如何将先前的输入作为此参数传递。

但是我已经尝试过email,,需要对象引用。我似乎不想在类本身中引用该类的实例,因此我尝试this.email但收到错误“关键字'this'在当前上下文中不可用”。

如果有人能帮助我找出Compare在我的情况下使用该课程的正确方法,我将非常感激。否则,如果我找错了树,请告诉我。谢谢!

Xee*_*vis 3

对于 Blazor 应用程序,Microsoft 创建了新的 NuGet 包Microsoft.AspNetCore.Components.DataAnnotations.Validation以便与DataAnnotationsValidator组件一起使用。该库[CompareProperty]在与以前的[Compare]属性相同的命名空间中定义属性,它是直接替换的。

工作示例:

@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; }
    }
}

Run Code Online (Sandbox Code Playgroud)

您可以在文档中详细了解为什么[Compare]Blazor 应用不需要使用属性。

  • 我从 Google 来到这里,所以值得注意 - 使用 `nameof(Email)` 作为 `CompareProperty` 构造函数的参数是明智的,因为它更能抵抗重构。 (2认同)