59 lines
1.6 KiB
C#
59 lines
1.6 KiB
C#
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// IsValid 为 false 时,提示得 error 信息
|
|
/// </summary>
|
|
/// <param name="name"></param>
|
|
/// <returns></returns>
|
|
public override string FormatErrorMessage(string name)
|
|
{
|
|
var lengthMessage = LengthError ? $",且长度不能超过{Length}" : "";
|
|
return $"{name}必须输入数字{lengthMessage},请重新输入!";
|
|
}
|
|
|
|
/// <summary>
|
|
/// 验证当前字段得结果
|
|
/// </summary>
|
|
/// <param name="value"></param>
|
|
/// <returns></returns>
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
}
|