mvc3验证检查属性值是否不同

adr*_*nos 4 c# validation asp.net-mvc-3

在MVC3中,您可以向模型添加验证,以检查属性是否匹配如下:

public string NewPassword { get; set; }

[Compare("NewPassword", 
ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
Run Code Online (Sandbox Code Playgroud)

有没有办法检查两个属性是否有所不同,如下面的假设代码?

[CheckPropertiesDiffer("OldPassword", 
ErrorMessage = "Old and new passwords cannot be the same")]
public string OldPassword { get; set; }

public string ConfirmPassword { get; set; }
Run Code Online (Sandbox Code Playgroud)

ysr*_*srb 6

我会检查控制器.

在控制器中:

if(model.ConfirmPassword == model.OldPassword ){
  ModelState.AddModelError("ConfirmPassword", "Old and new passwords cannot be the same");
}
Run Code Online (Sandbox Code Playgroud)

在视图中:

@Html.ValidationMessage("ConfirmPassword")
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助