21 Model 验证 Again.mp4 (52.11MB)

自定义验证 Attribute

  • Attribute,IModelValidator

示例:ValidUrlAttribute

  1. public class ValidUrlAttribute : Attribute, IModelValidator
  2. {
  3. public string ErrorMessage { get; set; }
  4. public IEnumerable<ModelValidationResult> Validate(
  5. ModelValidationContext context)
  6. {
  7. var url = context.Model as string;
  8. if (url != null && Uri.IsWellFormedUriString(url, UriKind.Absolute))
  9. {
  10. return Enumerable.Empty<ModelValidationResult>();
  11. }
  12. return new List<ModelValidationResult>
  13. {
  14. new ModelValidationResult(string.Empty, ErrorMessage)
  15. };
  16. }
  17. }

使用时标注在 ViewModel 等实体类的属性上即可:

  1. [Display(Name = "封面地址")]
  2. [Required(ErrorMessage = "{0}是必填项"), MaxLength(200, ErrorMessage = "{0}的长度不可超过{1}")]
  3. //[DataType(DataType.Url)]
  4. [ValidUrl(ErrorMessage = "这个URL不正确")]
  5. public string CoverUrl { get; set; }

远程验证

  • [Remote]
  • 客户端调用 Action 方法进行验证(前台调用后台验证)

Action 中的方法:

  1. [AcceptVerbs("Get", "Post")]
  2. public async Task<IActionResult> CheckRoleExist([Bind("RoleName")]string roleName)
  3. {
  4. var role = await _roleManager.FindByNameAsync(roleName);
  5. if (role != null) return Json("角色已经存在了");
  6. return Json(true);
  7. }

标注属性:

  1. public class RoleAddViewModel
  2. {
  3. [Required]
  4. [Display(Name = "角色名称")]
  5. [Remote(nameof(RoleController.CheckRoleExist), "Role", ErrorMessage = "角色已存在")]
  6. public string RoleName { get; set; }
  7. }

注:暂时没找到更优雅的方法获取到 “Role”。