看到一篇讲到更好的【译】MVC3 20个秘方-(3)验证用户的输入
MVC 中自带了用户输入验证功能,在命名空间System.ComponentModel.DataAnnotations
这样使用
[Required] [Display(Name = "User name")] public string UserName { get; set; }
对特殊的验证需要自定义数据标注
public class MaxWordsAttribute : ValidationAttribute { private readonly int _maxWords; public MaxWordsAttribute(int maxWords):base("{0} too many words.") { _maxWords = maxWords; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if(value!=null) { var valueAsString = value.ToString(); if (valueAsString.Split(' ').Length > _maxWords) { var errorMessage=FormatErrorMessage(validationContext.DisplayName); return new ValidationResult(errorMessage); } } return ValidationResult.Success; } }
使用
[Required] [Display(Name = "User name")] [MaxWords(2,ErrorMessage="{0} 太多单词了")] public string UserName { get; set; }