0
我试图比较密码并使用验证属性在表单上确认密码,但是当我在两个字段上使用不同值提交表单时,错误不会显示在旁边确认密码字段。Asp.net mvc4验证检查属性值是否相同
我试过这个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));
}
}
}
请发表您的代码样本,以便我们能够决定到哪里去错误的。 –
确保您使用的是正确的Compare属性。我发现在标准库的典型MVC安装中至少可以看到两个。 –
我已经添加了源代码@DanNeely – user2627722