由于系统的数据注解肯定不适合所有的场合,所以有时候我们需要自定义数据注解。
public class MyMaxLengthAttribute : ValidationAttribute
{
private readonly int MaxLength;
public MyMaxLengthAttribute(int maxLength)
{
MaxLength = maxLength;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string content = value.ToString();
if (content.Length > MaxLength)
{
return new ValidationResult("输入的字符太多了!^_^");
}
return ValidationResult.Success;
//return base.IsValid(value, validationContext);
}
[Required(ErrorMessageResourceType=typeof(ErrorMessage),ErrorMessageResourceName="UserRequire")]
[Display(Name = "用户名")]
[MyMaxLengthAttribute(10)]
[Remote("CheckUserName","Account", HttpMethod="POST")]
public string UserName { get; set; }

[Required(ErrorMessageResourceType=typeof(ErrorMessage),ErrorMessageResourceName="UserRequire")]
[Display(Name = "用户名")]
[MyMaxLengthAttribute(10,ErrorMessage="{0}字数太多")]
[Remote("CheckUserName","Account", HttpMethod="POST")]
public string UserName { get; set; }
public class MyMaxLengthAttribute : ValidationAttribute
{
private readonly int MaxLength;
public MyMaxLengthAttribute(int maxLength ):base("{0}的字符太多了!")
{
MaxLength = maxLength;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string content = value.ToString();
if (content.Length > MaxLength)
{
//return new ValidationResult("输入的字符太多了!^_^");
string errorMessage = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(errorMessage);
}
return ValidationResult.Success;
//return base.IsValid(value, validationContext);
}
}

public IEnumerable<ValidationResult> Validate(ValidationContext validationContent)
{
if (Password != ConfirmPassword)
{
yield return new ValidationResult("两次输入的密码不同!", new[] { "Password" });
}
}
这个方法在提交Model时会自动验证两次输入的密码是否相同,如果不同则会提示,如下:

原文:http://www.cnblogs.com/yaosuc/p/4528034.html