平安校园
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

66 regels
1.5 KiB

  1. //
  2. namespace SafeCampus.System;
  3. /// <summary>
  4. /// 验证值是否在字典中,大数据慎用
  5. /// </summary>
  6. public class InDictAttribute : ValidationAttribute
  7. {
  8. public InDictAttribute(string dictValue)
  9. {
  10. DictValue = dictValue;
  11. }
  12. /// <summary>
  13. /// 字典值
  14. /// </summary>
  15. public string DictValue { get; set; }
  16. /// <summary>
  17. /// 获取错误信息
  18. /// </summary>
  19. /// <param name="value">值</param>
  20. /// <returns></returns>
  21. public string GetErrorMessage(string value)
  22. {
  23. if (string.IsNullOrEmpty(ErrorMessage))
  24. {
  25. switch (DictValue)
  26. {
  27. case SysDictConst.GENDER:
  28. return "性别只能是男和女";
  29. case SysDictConst.NATION:
  30. return "不存在的民族";
  31. default:
  32. return $"字典中不存在{value}";
  33. }
  34. }
  35. return ErrorMessage;
  36. }
  37. protected override ValidationResult IsValid(object value, ValidationContext validationContext)
  38. {
  39. if (value != null)
  40. {
  41. var dictService = App.GetService<IDictService>();
  42. var values = dictService.GetValuesByDictValue(DictValue).Result;
  43. if (!values.Contains(value))
  44. {
  45. return new ValidationResult(GetErrorMessage(value.ToString()), new[] { validationContext.MemberName });
  46. }
  47. }
  48. return ValidationResult.Success;
  49. }
  50. }