比较密码并确认密码在我的代码中不起作用?

时间:2018-07-23 10:13:19

标签: c# asp.net-mvc

比较密码并确认密码在我的代码中不起作用

 [Required]
 [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
 [DataType(DataType.Password)]
 [Display(Name = "Password")]
 public string Password { get; set; }

 [DataType(DataType.Password)]
 [Display(Name = "Confirm password")]
 [StringLength(100, ErrorMessage = "The Password didn't match.")]
 [Compare("Password")]
 public string ConfirmPassword { get; set; }

当我在确认密码中输入了错误的密码时,我在这里使用Compare属性来匹配我的密码并确认密码。

1 个答案:

答案 0 :(得分:2)

为了显示错误消息,当ConfirmPassword不正确时,您应该在Compare属性内(而不是StringLength属性内)指定错误消息:

[Compare("Password", ErrorMessage = "The Password didn't match.")]
public string ConfirmPassword { get; set; }

我也建议使用nameof来指定比较属性名称:

[Compare(nameof(Password), ErrorMessage = "The Password didn't match.")]
public string ConfirmPassword { get; set; }