Merge pull request '😃perf(特性):简化身份证特性校验代码' (#405) from ir0nmax/Admin.NET.Pro:v2 into v2
Reviewed-on: https://code.adminnet.top/Admin.NET/Admin.NET.Pro/pulls/405
This commit is contained in:
commit
525253b866
@ -10,44 +10,22 @@ namespace Admin.NET.Core;
|
||||
/// 身份证号码合规性校验特性
|
||||
/// </summary>
|
||||
[SuppressSniffer]
|
||||
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
|
||||
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = true)]
|
||||
public class IdCardNoAttribute : ValidationAttribute
|
||||
{
|
||||
/// <summary>
|
||||
/// 是否允许空字符串
|
||||
/// </summary>
|
||||
[Obsolete("参数已废弃,逻辑已删除,请使用[Required]特性校验必填")]
|
||||
public bool AllowEmptyStrings { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// 允许空值,有值才验证,默认 false
|
||||
/// </summary>
|
||||
[Obsolete("参数已废弃,逻辑已删除,请使用[Required]特性校验必填")]
|
||||
public bool AllowNullValue { get; set; } = false;
|
||||
|
||||
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
|
||||
{
|
||||
// 判断是否允许空值
|
||||
if (IsEmpty(value)) return ValidationResult.Success;
|
||||
// 检查目标类型是否为字符串
|
||||
if (value != null && value is not string)
|
||||
return new ValidationResult($"{validationContext.DisplayName} 必须是字符串类型");
|
||||
|
||||
// 可空,或者通过验证
|
||||
string idCardNo = value?.ToString();
|
||||
|
||||
if (!IdCardHelper.CheckIdCard(idCardNo))
|
||||
return new ValidationResult($"身份证号格式不正确");
|
||||
|
||||
return ValidationResult.Success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断值是否为空(null、空字符串、空集合)
|
||||
/// </summary>
|
||||
private static bool IsEmpty(object? value)
|
||||
{
|
||||
return value switch
|
||||
if (string.IsNullOrEmpty(idCardNo) || IdCardHelper.CheckIdCard(idCardNo))
|
||||
{
|
||||
null => true,
|
||||
string s => string.IsNullOrWhiteSpace(s),
|
||||
IList list => list.Count == 0,
|
||||
_ => false
|
||||
};
|
||||
return ValidationResult.Success;
|
||||
}
|
||||
|
||||
return new ValidationResult($"身份证号格式不正确");
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user