asp.net mvc3 数据验证(三)—自定义数据注解
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" }); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。