From 0bae9c9943a2ca6f87e0baea8f0c8043092e5a73 Mon Sep 17 00:00:00 2001 From: falcon <9504402@qq.com> Date: Thu, 24 Nov 2022 10:57:57 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=A8=A1=E5=9E=8B=E9=AA=8C?= =?UTF-8?q?=E8=AF=81IsIntAttribute=EF=BC=8C=E8=A1=A8=E7=A4=BA=E5=B1=9E?= =?UTF-8?q?=E6=80=A7=E5=80=BCToString=E5=90=8E=E5=BF=85=E9=A1=BB=E5=8F=AF?= =?UTF-8?q?=E8=BD=AC=E6=8D=A2=E4=B8=BAInt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ModelValidation/IsIntAttribute.cs | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Falcon.SugarApi/ModelValidation/IsIntAttribute.cs diff --git a/Falcon.SugarApi/ModelValidation/IsIntAttribute.cs b/Falcon.SugarApi/ModelValidation/IsIntAttribute.cs new file mode 100644 index 0000000..baf35fc --- /dev/null +++ b/Falcon.SugarApi/ModelValidation/IsIntAttribute.cs @@ -0,0 +1,28 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; + +namespace Falcon.SugarApi.ModelValidation +{ + /// + /// 必须可转换为整数 + /// + public class IsIntAttribute : ValidationAttribute + { + /// + public override bool IsValid(object? value) { + if (value == null) { + return false; + } + return int.TryParse(value.ToString(), out int _); + } + + /// + protected override ValidationResult? IsValid(object? value, ValidationContext validationContext) { + if (value == null) { + return new ValidationResult(ErrorMessage = "必须为整数"); + } + return this.IsValid(value) ? null + : new ValidationResult(ErrorMessage = "必须为整数", new List() { validationContext.MemberName }); + } + } +}