//
namespace SafeCampus.System;
///
/// 验证值是否在字典中,大数据慎用
///
public class InDictAttribute : ValidationAttribute
{
public InDictAttribute(string dictValue)
{
DictValue = dictValue;
}
///
/// 字典值
///
public string DictValue { get; set; }
///
/// 获取错误信息
///
/// 值
///
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();
var values = dictService.GetValuesByDictValue(DictValue).Result;
if (!values.Contains(value))
{
return new ValidationResult(GetErrorMessage(value.ToString()), new[] { validationContext.MemberName });
}
}
return ValidationResult.Success;
}
}