ASP.NET MVC 4跨字段或属性验证

时间:2013-03-17 19:58:20

标签: c# asp.net asp.net-mvc

我试图弄清楚如何验证用户在注册时输入了匹配的密码。我可以使用MVC 4数据注释内置的任何东西,或者是创建自定义验证属性的唯一途径吗?

如果我必须创建自定义验证属性,如何访问密码属性(假设我将注释放在确认密码属性上)?此外,是否有任何常用的库用于此类验证?

这就是我在自定义验证属性的开头所拥有的,只是不知道如何访问密码属性:

public class CrossFieldValidationAttribute : ValidationAttribute
{
    public override bool IsValid(object value) //how do I get the other value in here?
    {
        //validation logic here
        return base.IsValid(value);
    }
}

我感谢任何帮助!

4 个答案:

答案 0 :(得分:10)

mvc中已经内置了比较验证属性。请参阅此处的文档:

http://msdn.microsoft.com/en-us/library/system.web.mvc.compareattribute(v=vs.98).aspx

使用的一个例子是:

    public string Password { get; set; }

    [Compare("Password", ErrorMessage = "Uh oh")]
    public string PasswordAgain { get; set; }

答案 1 :(得分:2)

您可以创建自定义属性并为其公共属性设置其他信息。

public class CustomValidationAttribute : ValidationAttribute
{
    public string MeaningfulValidationInfo { get; set; }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // do whatever meaningful with MeaningfulValidationInfo 
        return base.IsValid(value, validationContext);
    }
}

您可以通过这种方式设置其他信息:

[CustomValidationAttribute(MeaningfulValidationInfo = "blah")]
public ActionResult Index()
{
    return View();
}

如果您要检查两个输入的密码是否相同,您只需在模型中验证它。

    public class LoginModel
    {
        [Required]
        [EmailAddress]
        public string EmailAddress { get; set; }
        [Required]
        public string Password { get; set; }
        [Required]
        [Compare("Password")]
        [Display(Name = "Confirm password")]
        public string ConfirmPassword { get; set; }
    }
}

答案 2 :(得分:1)

比较注释是最简单的选择。如下所示,Compare指向Password属性。

[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")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }

答案 3 :(得分:-2)

您可以使用ASP.NET工具中内置的* 比较验证* 控件

我在下面提供了一个示例

<body>
    <form id="form1" runat="server">
    <div>

    <asp:Label
        id="lblBirthDate"
        Text="Birth Date:"
        AssociatedControlID="txtBirthDate"
        Runat="server" />
    <asp:TextBox
        id="txtBirthDate"
        Runat="server" />
    <asp:CompareValidator
        id="cmpBirthDate"
        Text="(Invalid Date)"
        ControlToValidate="txtBirthDate"
        Type="Date"
        Operator="DataTypeCheck"
        Runat="server" />

    <br /><br />

    <asp:Button
        id="btnSubmit"
        Text="Submit"
        Runat="server" />

    </div>
    </form>
</body>

请参阅以下任何链接以扩大您的知识

http://www.java2s.com/Tutorial/ASP.NET/0160__Validation/CompareValidatorperformsthreedifferenttypesofvalidations.htm

http://www.vkinfotek.com/aspnetvalidationcontrols.html