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" }); } }