Код: Выделить всё
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class MinByteLengthAttribute(string lengthPropertyName) : ValidationAttribute
{
public override bool RequiresValidationContext => true;
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var lengthProperty = validationContext.ObjectType.GetProperty(lengthPropertyName, BindingFlags.Instance | BindingFlags.Public) ?? throw new ArgumentException($"Property '{lengthPropertyName}' not found on type '{validationContext.ObjectType.Name}'.");
var minLength = (int)lengthProperty.GetValue(validationContext.ObjectInstance);
if (value is not byte[] bytes || bytes.Length < minLength)
{
var errorMessage = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(errorMessage);
}
return ValidationResult.Success;
}
}
< /code>
и украсить свойство с ним: < /p>
public int ImageMinSize { get; set; } = 10000;
[Required(ErrorMessageResourceType = typeof(Validation), ErrorMessageResourceName = "ImageRequired")]
[MinByteLength(nameof(ImageMinSize), ErrorMessageResourceType = typeof(Validation), ErrorMessageResourceName = "ImageTooSmall")]
public byte[] Image { get; set; }
Код: Выделить всё
< /code>
и как стандарт, у меня есть: < /p>
Я что -то упускаю?
Подробнее здесь: https://stackoverflow.com/questions/797 ... or-message