c# - ASP MVC : Custom Validation Attribute

标签 c# asp.net-mvc validation asp.net-mvc-2 attributes

我正在尝试编写自己的自定义验证属性,但遇到了一些问题。

我想写的属性是当用户登录时,密码将与确认密码进行比较。

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/

相关文章:

PHP 检查某些键或值是否在多维数组中

MySQL 左外连接验证?

c# - 该字段必须是数字

c# - C# 中的自然排序顺序

c# - ASP.NET MVC Windows Authentiaction 和 DirectoryServices - 获取当前用户的邮件地址引发 InvalidCastException

asp.net-mvc - 在 Razor View 中,我怎样才能拥有诸如 <span id ='cat@MYID'/> 之类的控件?

c# - Rhino Mocks——断言不与模拟/ stub 交互

c# - 缺少 ASP.net MVC FormsAuthentication cookie

c# - 如何使div整个页面宽度并将其他元素向下移动?

forms - Laravel:多个文件上传,Input::hasFile(key) 始终为 false