增加模型验证IsIntAttribute,表示属性值ToString后必须可转换为Int

This commit is contained in:
falcon 2022-11-24 10:57:57 +08:00
parent d49a382aab
commit 0bae9c9943

View File

@ -0,0 +1,28 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Falcon.SugarApi.ModelValidation
{
/// <summary>
/// 必须可转换为整数
/// </summary>
public class IsIntAttribute : ValidationAttribute
{
/// <inheritdoc />
public override bool IsValid(object? value) {
if (value == null) {
return false;
}
return int.TryParse(value.ToString(), out int _);
}
/// <inheritdoc />
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<string>() { validationContext.MemberName });
}
}
}