避免重复不同形式的字段

时间:2015-02-23 22:33:02

标签: c# asp.net-mvc asp.net-mvc-5 viewmodel

我现在在三个项目中遇到过这个问题。我有多个表单引用相同的数据字段,但有不同的显示。对于下面的示例,我正在更新或引用AspNetUser表,从创建新用户,编辑配置文件,登录等。如果我尝试单个基本视图模型,我遇到了必填字段的问题。

因此,例如,这里是用户名和密码/确认

的字段
[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; }

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

有人有办法处理这个问题吗?

1 个答案:

答案 0 :(得分:0)

我找到了一个我很满意的解决方案。我使用具有复杂验证的字段创建一个接口,然后我使用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; }

}

我将密码的显示名称保留在界面之外,以便在编辑用户时可以将其命名为新密码,而在创建用户时可以将其命名为密码