2012-07-25 74 views
1
public class User 
{ 
string username; 
string password; 
} 

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

它产生错误(找不到属性) 有没有办法为另一个类中的属性创建验证?MVC3模型验证(在另一个类比较属性格式)

感谢

+0

我刚刚找到了如何创建自定义的验证。 – 2012-07-25 18:48:07

+2

请发布您的答案,以便可以帮助其他人 – VJAI 2012-07-26 03:16:56

回答

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

}

+0

可能有更好的方法来做到这一点,但这是我所做的 – 2012-07-27 13:38:41