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 LongValidationAttribute : ValidationAttribute
{
public int? Length { get; }
private bool LengthError { get; set; }
public LongValidationAttribute()
{
}
public LongValidationAttribute(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 (long.TryParse(Convert.ToString(value), out long num))
{
if (Length != null && num.ToString().Length > Length)
{
LengthError = true;
return false;
}
return true;
}
else
{
return false;
}
}
}
}