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

本文关键字:是否 属性 检查 net mvc4 验证 Asp | 更新日期: 2023-09-27 18:25:18

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

我已经尝试过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));
        }   
    }
} 

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

您可以使用compare属性来确认密码:

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