ASP.NET MVC 4跨字段或属性验证 [英] ASP.NET MVC 4 Cross field or property validation

查看:162
本文介绍了ASP.NET MVC 4跨字段或属性验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何验证用户在注册时是否输入了匹配的密码.我可以为此使用MVC 4数据注释中内置的任何内容,还是创建自定义验证属性的唯一途径?

I'm trying to figure out how to validate that a user has entered matching passwords when they sign up. Is there anything built in to MVC 4 Data Annotations that I can use for this or is the only route creating a custom validation attribute?

如果我必须创建一个自定义验证属性,该如何访问password属性(假设我将注释放在Confirm password属性上)?另外,是否有用于此类验证的常用库?

If I do have to create a custom validation attribute, how do I access the password property (assuming I put the annotation on the confirm password property)? Also, are there any commonly used libraries for this type of validation?

这是我自定义验证属性开头的内容,只是不确定如何访问密码属性:

This is what I have for the beginning of a custom validation attribute, just not sure how to access the password property:

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);
    }
}

感谢您的帮助!

推荐答案

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

You can create custom attributes and set additional information to their public properties.

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);
    }
}

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

You'd set the additional info this way:

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

如果您要检查两个输入的密码是否相同,则只需在模型中进行验证即可.

If you are trying to check if both entered passwords were identical, you can simply validate that in your model.

    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; }
    }
}

这篇关于ASP.NET MVC 4跨字段或属性验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆