From 1080ec882030f0f73dbfc63ad5df494b3d73cd7a Mon Sep 17 00:00:00 2001 From: Ir0nMax Date: Mon, 18 Aug 2025 15:22:09 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=98=83perf(=E7=89=B9=E6=80=A7):=E7=AE=80?= =?UTF-8?q?=E5=8C=96=E8=BA=AB=E4=BB=BD=E8=AF=81=E7=89=B9=E6=80=A7=E6=A0=A1?= =?UTF-8?q?=E9=AA=8C=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Attribute/IdCardNoAttribute.cs | 44 +++++-------------- 1 file changed, 11 insertions(+), 33 deletions(-) diff --git a/Admin.NET/Admin.NET.Core/Attribute/IdCardNoAttribute.cs b/Admin.NET/Admin.NET.Core/Attribute/IdCardNoAttribute.cs index c158c8df..08120cd2 100644 --- a/Admin.NET/Admin.NET.Core/Attribute/IdCardNoAttribute.cs +++ b/Admin.NET/Admin.NET.Core/Attribute/IdCardNoAttribute.cs @@ -10,44 +10,22 @@ namespace Admin.NET.Core; /// 身份证号码合规性校验特性 /// [SuppressSniffer] -[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = true)] public class IdCardNoAttribute : ValidationAttribute { - /// - /// 是否允许空字符串 - /// - [Obsolete("参数已废弃,逻辑已删除,请使用[Required]特性校验必填")] - public bool AllowEmptyStrings { get; set; } = false; - - /// - /// 允许空值,有值才验证,默认 false - /// - [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; - } - - /// - /// 判断值是否为空(null、空字符串、空集合) - /// - 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($"身份证号格式不正确"); } } \ No newline at end of file