6 c# validation asp.net-mvc attributes asp.net-mvc-2
我正在尝试编写自己的自定义验证属性,但我遇到了一些问题.
我试图写的属性是当用户登录时,密码将与确认密码进行比较.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我的问题是当我试图在模型文件中设置这样的属性时:
[Required]
[ComparePassword(PasswordToCompareWith=ConfirmPassword)]
public string Password { get; set; }
[Required]
public string ConfirmPassword { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
错误1非静态字段,方法或属性'Project.Data.Models.GebruikerRegistreerModel.ConfirmPassword.get'需要对象引用
似乎VS不接受confirmpassword该PasswordToCompareWith=ConfirmPassword部分.
我究竟做错了什么?
orc*_*rcy 18
根据这个链接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; }
}
Run Code Online (Sandbox Code Playgroud)
CompareAttribute是一个新的,非常有用的验证器,它实际上不是System.ComponentModel.DataAnnotations的一部分,但已被团队添加到System.Web.Mvc DLL中.虽然没有特别好的命名(它唯一的比较是检查相等性,所以也许EqualTo会更明显),从使用中很容易看出这个验证器检查一个属性的值等于另一个属性的值.您可以从代码中看到,该属性接受一个字符串属性,该属性是您要比较的另一个属性的名称.这种验证器的经典用法是我们在这里使用它:密码确认.
| 归档时间: |
|
| 查看次数: |
36248 次 |
| 最近记录: |