|
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
-
- //
-
-
-
-
-
-
-
-
- namespace SafeCampus.System;
-
- /// <summary>
- /// 验证值是否在字典中,大数据慎用
- /// </summary>
- public class InDictAttribute : ValidationAttribute
- {
- public InDictAttribute(string dictValue)
- {
- DictValue = dictValue;
- }
-
- /// <summary>
- /// 字典值
- /// </summary>
- public string DictValue { get; set; }
-
- /// <summary>
- /// 获取错误信息
- /// </summary>
- /// <param name="value">值</param>
- /// <returns></returns>
- public string GetErrorMessage(string value)
- {
- if (string.IsNullOrEmpty(ErrorMessage))
- {
- switch (DictValue)
- {
- case SysDictConst.GENDER:
- return "性别只能是男和女";
-
- case SysDictConst.NATION:
- return "不存在的民族";
-
- default:
- return $"字典中不存在{value}";
- }
- }
- return ErrorMessage;
- }
-
- protected override ValidationResult IsValid(object value, ValidationContext validationContext)
- {
- if (value != null)
- {
- var dictService = App.GetService<IDictService>();
- var values = dictService.GetValuesByDictValue(DictValue).Result;
- if (!values.Contains(value))
- {
- return new ValidationResult(GetErrorMessage(value.ToString()), new[] { validationContext.MemberName });
- }
- }
- return ValidationResult.Success;
- }
- }
|