我正在尝试编写自己的自定义验证属性,但遇到了一些问题。
我想写的属性是当用户登录时,密码将与确认密码进行比较。
namespace Data.Attributes
{
public class ComparePassword : ValidationAttribute
{
public string PasswordToCompareWith { get; set; }
public override bool IsValid(object value)
{
if (PasswordToCompareWith == (string)value)
{
return true;
}
return false;
}
}
现在我的问题是当我试图在模型文件中设置这样的属性时:
[Required]
[ComparePassword(PasswordToCompareWith=ConfirmPassword)]
public string Password { get; set; }
[Required]
public string ConfirmPassword { get; set; }
}
我收到以下错误:
Error 1 An object reference is required for the non-static field, method, or property 'Project.Data.Models.GebruikerRegistreerModel.ConfirmPassword.get'
似乎 VS 不接受 PasswordToCompareWith=ConfirmPassword
部分中的 confirmpassword
。
我做错了什么?
最佳答案
根据此链接http://devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-1 MVC3 中现在有一个特殊的验证属性:
public class RegisterModel
{
// skipped
[Required]
[ValidatePasswordLength]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation do not match.")]
public string ConfirmPassword { get; set; }
}
CompareAttribute is a new, very useful validator that is not actually part of System.ComponentModel.DataAnnotations, but has been added to the System.Web.Mvc DLL by the team. Whilst not particularly well named (the only comparison it makes is to check for equality, so perhaps EqualTo would be more obvious), it is easy to see from the usage that this validator checks that the value of one property equals the value of another property. You can see from the code, that the attribute takes in a string property which is the name of the other property that you are comparing. The classic usage of this type of validator is what we are using it for here: password confirmation.
关于c# - ASP MVC : Custom Validation Attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2720735/