using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DG.Core { public class IntValidationAttribute : ValidationAttribute { public int? Length { get; } private bool LengthError { get; set; } public IntValidationAttribute() { } public IntValidationAttribute(int? length) { Length = length; } /// /// IsValid 为 false 时,提示得 error 信息 /// /// /// public override string FormatErrorMessage(string name) { var lengthMessage = LengthError ? $",且长度不能超过{Length}" : ""; return $"{name}必须输入数字{lengthMessage},请重新输入!"; } /// /// 验证当前字段得结果 /// /// /// public override bool IsValid(object? value) { if (value == null) return true; if (int.TryParse(Convert.ToString(value), out int num)) { if (Length != null && num.ToString().Length > Length) { LengthError = true; return false; } return true; } else { return false; } } } }