平安校园
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

InDictAttribute.cs 1.5 KiB

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