避免为不同的表单重复字段

Avoid duplicating fields for different forms

我现在 运行 参与了三个项目。我有多个表单引用相同的数据字段,但显示不同。对于下面的示例,我正在通过创建新用户、编辑个人资料、登录等更新或引用 AspNetUser table。如果我尝试使用单个基本视图模型,我会遇到必填字段的问题。

例如,这里是用户名和 Password/confirmation

的字段
[Required]
[RegularExpression(@"^[a-zA-Z0-9$$!%*#-_?&]*$", ErrorMessage = "The user name is invalid. Only letters, numbers, hyphens and underscores are allowed.")]
public string UserName { get; set; }

[Required]
[DataType(DataType.Password)]
[RegularExpression(@"^(?=.*[A-Z])(?=.[a-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{7,20}$",
    ErrorMessage = "Password must contain a number, a lowercase character, an uppercase character, a special character and be between 7 and 20 characters in length.")]
[Display(Name = "Password")]
public string NewPassword { get; set; }

[Required]
[DataType(DataType.Password)]
[Display(Name = "Confirm Password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }

显然从登录屏幕我不需要确认密码。在编辑个人资料页面中,您无法更新用户名。 我讨厌在多个地方使用相同的代码,如果密码或用户名的规则发生变化,我不想进入一堆视图模型来更新正则表达式。

谁有好的办法解决这个问题?

我找到了一个令我满意的解决方案。我创建了一个包含具有复杂验证的字段的接口,然后我使用 MetadataType 在特定的 ViewModel 中使用它。

interface IUserBase
{

    [RegularExpression(@"^[a-zA-Z0-9$$!%*_\-#?&]*$", ErrorMessage = "The user name is invalid. Only letters, numbers, hyphens and underscores are allowed.")]
    string UserName { get; set; }

    [DataType(DataType.Password)]
    [RegularExpression(@"^(?=.*[A-Z])(?=.[a-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{7,20}$",
        ErrorMessage = "Password must contain a number, a lowercase character, an uppercase character, a special character and be between 7 and 20 characters in length.")]
    string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm Password")]
    [Compare("Password", ErrorMessage = "The new password and confirmation password do not match.")]
    string ConfirmPassword { get; set; }
}

然后任何使用 UserName、Password 或 ConfirmPassword 的视图模型都按如下方式设置。

[MetadataType(typeof(IUserBase))]
public class NewUserViewModel
{
    [Required]
    public string UserName { get; set; }

    [Required]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Required]
    public string ConfirmPassword { get; set; }

}

我将密码的显示名称保留在界面之外,以便在编辑用户时可以调用它 New PasswordPassword创建用户时。