Код: Выделить всё
using FluentValidation;
namespace ASValidation.Validators.Common
{
public static class CommonValidators
{
// Validates address: max 200 chars, allowed chars only
public static IRuleBuilderOptions ValidateAddress(this IRuleBuilder rule)
{
return rule
.MaximumLength(200).WithMessage("Address cannot exceed 200 characters.")
.Matches(@"^[a-zA-Z0-9\s\-,.#]+$").WithMessage("Address contains invalid characters.");
}
// Validates captcha: required and must be true
public static IRuleBuilderOptions ValidateCaptcha(this IRuleBuilder rule)
{
return rule
.NotEmpty().WithMessage("Captcha is required.")
.Equal(true).WithMessage("Captcha must be verified.");
}
// Validates ID: required (not empty)
public static IRuleBuilderOptions ValidateId(this IRuleBuilder rule)
{
return rule
.NotEmpty()
.WithMessage("{PropertyName} is required.");
}
// Validates primary key ID: must not be default unless 0
public static IRuleBuilderOptions ValidatePrimaryKeyID(this IRuleBuilder rule)
{
return rule
.Must(id => id == 0 || id != default)
.WithMessage("{PropertyName} is required.");
}
// Validates custom ID: 5-20 chars, alphanumeric, no spaces, case insensitive
public static IRuleBuilderOptions ValidateCustomId(this IRuleBuilder rule)
{
return rule
.NotEmpty().WithMessage("ID is required.")
.MinimumLength(5).WithMessage("ID must be at least 5 characters long.")
.MaximumLength(20).WithMessage("ID must not exceed 20 characters.")
.Matches(@"^[a-zA-Z0-9]+$").WithMessage("ID must contain only alphanumeric characters and no spaces.")
.WithMessage("ID must be case insensitive.");
}
// Validates property is required (not empty)
public static IRuleBuilderOptions IsRequired(this IRuleBuilder rule)
{
return rule
.NotEmpty().WithMessage("{PropertyName} is required.");
}
// Validates page: must be greater than 0
public static IRuleBuilderOptions ValidatePage(this IRuleBuilder rule)
{
return rule
.GreaterThan(0)
.WithMessage("Page must be greater than 0.");
}
}
}
< /code>
Правила по потреблению структуры проверки в моем проекте API: < /p>
using ASValidation.Validators.Common;
using ASValidation.Validators.Entity;
using FluentValidation;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
namespace agentservice.Validators
{
public class SubmitAgencyDetailsRequestDTOValidator : AbstractValidator
{
public SubmitAgencyDetailsRequestDTOValidator()
{
RuleFor(x => x.AsAgencyId).ValidateId();
RuleFor(x => x.RegisteredEmailId).NotEmpty().ValidateEmail();
RuleFor(x => x.WebsiteURL).ValidateAgentWebsiteUrl().When(x => !string.IsNullOrWhiteSpace(x.WebsiteURL));
RuleFor(x => x.AccessMethods).NotEmpty().IsRequired();
RuleFor(x => x.TypeOfBusinessID).ValidateId();
}
}
}
Текущая реализация:
Код: Выделить всё
RuleFor(x => x.WebsiteURL)
.ValidateAgentWebsiteUrl()
.When(x => !string.IsNullOrEmpty(x.WebsiteURL)); // Want to simplify this
< /code>
Ожидаемая реализация < /p>
RuleFor(x => x.WebsiteURL)
.ValidateAgentWebsiteUrl()
.ValidateWhenNotEmpty(); // Custom extension method
Как я могу создать метод расширения validatewhennotempty () , который:
[*] Пропускает валидацию для нулевых/пустых струн
Работает с любой цепочкой валидатора (например, AplectAddes /> не запускает «Требуемые» ошибки для пустых полей < /li>
Общая версия, которая работает для всех типов данных < /li>
< /ul>
Подробнее здесь: https://stackoverflow.com/questions/796 ... empty-stri