Files
WCS/Cowain.Base/Attributes/MinLengthAttribute.cs
2026-03-02 09:08:20 +08:00

42 lines
1.2 KiB
C#

using Cowain.Base.Helpers;
using Ke.Bee.Localization.Localizer.Abstractions;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cowain.Base.Attributes
{
public class MinLengthAttribute : ValidationAttribute
{
private readonly ILocalizer _l;
public MinLengthAttribute(int length)
{
Length = length;
_l = ServiceLocator.GetRequiredService<ILocalizer>();
}
public MinLengthAttribute(int length, string messageKey) : this(length)
{
MessageKey = messageKey;
}
public int Length { get; }
public string? MessageKey { get; }
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
if (value is string stringValue && stringValue.Length < Length)
{
var errorMessage = string.IsNullOrEmpty(MessageKey) ? $"The length of the string should be at least {Length} characters" : _l[MessageKey] + Length;
return new ValidationResult(errorMessage);
}
return ValidationResult.Success;
}
}
}