Asp.net mvc4验证检查属性值是否相同

时间:2013-07-28 14:39:52

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

我尝试使用验证属性在表单上比较密码和确认密码,但是当我在两个字段上提交具有不同值的表单时,确认密码字段旁边不会显示错误。

我已经在question尝试了MVC3验证的方法,但它没有帮助。

以下是源代码:

//Model
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Globalization;
using System.Web.Security;
using System.Web.Mvc;
using mvcdemo.Validation;

namespace mvcdemo.Models
{
    public class User:IValidatableObject
    {
        public int userid { get; set; }
        [Required]
        [Remote("Username", "User",ErrorMessage = "The username is not allowed.")] //remote server validation asynchronous
        public string username { get; set; }
        public string password { get; set; }

        [PasswordCreationRule("password",ErrorMessage ="Password and Confirm Password have to be the same")]
        public string ConfirmPassword { get; set; }

        public string email { get; set; }
        public int roleid { get; set; }
        [Required]
        [Display(Name = "Password at first logon status")]
        public string passwordatfirstlogonstatus { get; set; }

    }

    public class UserDBContext : DbContext
    {
        public DbSet<User> users { get; set; }
    }
    public class administrator : User
    {

    }

}

// Validation class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.Reflection;

namespace mvcdemo.Validation
{
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class PasswordCreationRuleAttribute:ValidationAttribute
    {
        private const string defaultErrorMessage = "{0} cannot be different same as {1}.";
        private string otherProperty;
        public PasswordCreationRuleAttribute(string otherProperty): base(defaultErrorMessage)
        {
            if(string.IsNullOrEmpty(otherProperty))
            {
                throw new ArgumentNullException("otherProperty");

            }
            this.otherProperty = otherProperty;
        }
        public override string FormatErrorMessage(string name)
        {
            return string.Format(ErrorMessageString, name, otherProperty);
        }
        protected override ValidationResult IsValid(object value,ValidationContext validationContext)
        {
            if (value != null)
            {
                PropertyInfo otherPropertyInfo = validationContext.ObjectInstance.GetType().GetProperty(otherProperty);
                if (otherPropertyInfo == null)
                {
                    return new ValidationResult(string.Format("Property '{0}' is undefined.", otherProperty));
                }

                var otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);

                if (otherPropertyValue != null)
                {
                    if (value.Equals(otherPropertyValue))
                    {
                        return ValidationResult.Success;
                    }
                    else
                    {
                        return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));

                    }
                }
            }
                return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));

        }   
    }
} 

1 个答案:

答案 0 :(得分:0)

您可以使用比较属性确认密码:

public string password { get; set; }

[Compare("Password", ErrorMessage = "Password and Confirm Password have to be the same")]
public string ConfirmPassword { get; set; }