Zxd.Core/code/DG.Core/Validation/LongValidationAttribute.cs

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