Avoid duplicate fields for different forms

Now I came across this in three projects. I have several forms that reference the same data fields, but have different mappings. In the example below, I am updating or referencing the AspNetUser table, creating a new user, editing the profile, login, etc. If I try to use one basic view model, I am having problems with required fields.

So, for example, here are the fields for username and 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; }

, . . , , .

- ?

+4
1

, . , , MetadataType ViewModels.

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

}

, " " , .

0

All Articles