MVC3 模型验证(比较另一个类中的属性)


public class User
{
string username;
string password;
}
public class registration
{
User user;
**[compare(user.password)]**
string newPass;
}

它产生错误(找不到属性(有没有办法为另一个类中的属性创建验证?

谢谢

public class CompareOther:ValidationAttribute, IClientValidatable
{
private readonly string testedPropertyName;
private readonly string className;
public CompareOther(string testedPropertyName)
{
    string[] word = testedPropertyName.Split('.');
    this.testedPropertyName = word[1];
    this.className = word[0];
}
protected override ValidationResult IsValid(object value, ValidationContext     validationContext)
{
    var propertyTestedInfo = validationContext.ObjectType.GetProperty(this.className);
    if (propertyTestedInfo == null)
    {
        //return new ValidationResult("unknown property");
        return new ValidationResult(string.Format("unknown property {0}.{1}",this.className ,this.testedPropertyName));
    }
    var propertyObject = propertyTestedInfo.GetValue(validationContext.ObjectInstance,null);
    var propertyTestedValue = getValue(testedPropertyName,propertyObject);

    if (value == null)
    {
        return ValidationResult.Success;
    }
    if (propertyTestedValue == null)
    {
        return ValidationResult.Success;
    }
    if (propertyTestedValue.ToString() == value.ToString())
    {
        return ValidationResult.Success;
    }

   return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); 
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
    var rule = new ModelClientValidationRule
    {
        ErrorMessage = this.ErrorMessageString,
        ValidationType = "lessthan"
    };
    rule.ValidationParameters["propertytested"] = this.testedPropertyName;
    yield return rule;
}
private Object getValue(string name,Object obj)
{
    if (obj == null)
        return null;
    Type type = obj.GetType();
    PropertyInfo info = type.GetProperty(name);
    if (info == null)
    { return null; }
    obj = info.GetValue(obj, null);
    return obj;
}

}

最新更新