v1.31.0
conocimientogenerador-crudtemplates/7155 B

Validator.cs.template

Fichero que /hv:generador-crud usa o materializa en el proyecto. Se muestra tal cual está en el plugin.

generador-crudskill
templatescarpeta
7155 Btamaño
2026-10-03último cambio del pack
// ============================================================================
// TEMPLATE: Validator.cs - Validadores con FluentValidation (por entidad)
// Skill: generador-crud (ADR-031)
// ============================================================================
// USO: Reemplazar {{Entity}}, {{Entities}}, {{Namespace}} y los fragmentos {{ReglasValidacionCrear}},
//      {{MetodosValidacionAsync}}, {{ReglasValidacionActualizar}}, {{MetodosValidacionAsyncActualizar}}
// Destino: src/Application/Features/{{Entities}}/Validators/{{Entity}}Validators.cs
// Validan los Commands. Se ejecutan por pipeline de Mediator (behavior de validacion) o, en Minimal API,
// con el filtro WithValidation<T>() de EndpointFilters.cs. Los mensajes van en ingles (ADR-001, ADR-027).
// ============================================================================

using FluentValidation;
using {{Namespace}}.Application.Common.Interfaces;
using {{Namespace}}.Domain.Repositories;
using {{Namespace}}.Application.Features.{{Entities}}.Commands;

namespace {{Namespace}}.Application.Features.{{Entities}}.Validators;

// ═══════════════════════════════════════════════════════════════════════════
// VALIDATOR PARA CREAR
// ═══════════════════════════════════════════════════════════════════════════

public class Create{{Entity}}CommandValidator : AbstractValidator<Create{{Entity}}Command>
{
    private readonly I{{Entity}}Repository _repository;

    public Create{{Entity}}CommandValidator(I{{Entity}}Repository repository)
    {
        _repository = repository;

        {{ReglasValidacionCrear}}
    }

    // Validaciones asíncronas (unicidad contra el repositorio, etc.)
    {{MetodosValidacionAsync}}
}

// ═══════════════════════════════════════════════════════════════════════════
// VALIDATOR PARA ACTUALIZAR
// ═══════════════════════════════════════════════════════════════════════════

public class Update{{Entity}}CommandValidator : AbstractValidator<Update{{Entity}}Command>
{
    private readonly I{{Entity}}Repository _repository;

    public Update{{Entity}}CommandValidator(I{{Entity}}Repository repository)
    {
        _repository = repository;

        RuleFor(x => x.Id)
            .GreaterThan(0).WithMessage("Id is required")
            .MustAsync(ExistAsync).WithMessage("{{Entity}} not found");

        {{ReglasValidacionActualizar}}
    }

    private async Task<bool> ExistAsync(int id, CancellationToken ct)
    {
        return await _repository.ExistsAsync(id, ct);
    }

    {{MetodosValidacionAsyncActualizar}}
}

// ═══════════════════════════════════════════════════════════════════════════
// PATRONES DE VALIDACIÓN COMUNES
// ═══════════════════════════════════════════════════════════════════════════
/*
// STRINGS - obligatorios
RuleFor(x => x.Name)
    .NotEmpty().WithMessage("Name is required")
    .MaximumLength(200).WithMessage("Name must not exceed {MaxLength} characters")
    .MinimumLength(3).WithMessage("Name must be at least {MinLength} characters long");

// STRINGS - opcionales con formato
RuleFor(x => x.Email)
    .EmailAddress().WithMessage("Email format is invalid")
    .When(x => !string.IsNullOrEmpty(x.Email));

// STRINGS - regex
RuleFor(x => x.Code)
    .NotEmpty().WithMessage("Code is required")
    .Matches(@"^[A-Z]{3}-\d{4}$").WithMessage("Code must match the format XXX-0000");

// NÚMEROS - rango
RuleFor(x => x.Amount)
    .GreaterThan(0).WithMessage("Amount must be positive")
    .LessThanOrEqualTo(100000).WithMessage("Amount must not exceed {ComparisonValue}");

// NÚMEROS - precisión decimal
RuleFor(x => x.Percentage)
    .InclusiveBetween(0, 100).WithMessage("Percentage must be between 0 and 100")
    .PrecisionScale(5, 2, false).WithMessage("At most 2 decimals");

// FECHAS - futuro / comparación
RuleFor(x => x.StartDate)
    .GreaterThanOrEqualTo(DateOnly.FromDateTime(DateTime.Today)).WithMessage("Start date must be today or later");
RuleFor(x => x.EndDate)
    .GreaterThan(x => x.StartDate).WithMessage("End date must be after start date");

// ENUMS
RuleFor(x => x.Status)
    .IsInEnum().WithMessage("Status is not valid");

// COLECCIONES
RuleFor(x => x.Items)
    .NotEmpty().WithMessage("At least one item is required")
    .Must(x => x.Count <= 100).WithMessage("At most 100 items");

// VALIDACIÓN CONDICIONAL
RuleFor(x => x.DocumentNumber)
    .NotEmpty().WithMessage("Document number is required")
    .When(x => x.DocumentType == DocumentType.Passport);

// VALIDACIÓN ASYNC - unicidad
RuleFor(x => x.Code)
    .MustAsync(async (code, ct) => !await _repository.ExistsCodeAsync(code, ct))
    .WithMessage("Code is already in use");

// VALIDADOR ANIDADO / CADA ELEMENTO
RuleFor(x => x.Address).SetValidator(new AddressValidator());
RuleForEach(x => x.Items).SetValidator(new ItemValidator());
*/

// ============================================================================
// EJEMPLO GENERADO - ScholarshipValidators
// ============================================================================
/*
public class CreateScholarshipCommandValidator : AbstractValidator<CreateScholarshipCommand>
{
    private readonly IScholarshipRepository _repository;

    public CreateScholarshipCommandValidator(IScholarshipRepository repository)
    {
        _repository = repository;

        RuleFor(x => x.Code)
            .NotEmpty().WithMessage("Code is required")
            .MaximumLength(20).WithMessage("Code must not exceed {MaxLength} characters")
            .Matches(@"^[A-Z0-9-]+$").WithMessage("Code may only contain uppercase letters, digits and hyphens")
            .MustAsync(CodeIsFreeAsync).WithMessage("A scholarship with this code already exists");

        RuleFor(x => x.Name)
            .NotEmpty().WithMessage("Name is required")
            .MaximumLength(200).WithMessage("Name must not exceed {MaxLength} characters");

        RuleFor(x => x.Amount)
            .GreaterThan(0).WithMessage("Amount must be greater than 0");

        RuleFor(x => x.EndDate)
            .GreaterThan(x => x.StartDate).WithMessage("End date must be after the start date");
    }

    private async Task<bool> CodeIsFreeAsync(string code, CancellationToken ct)
    {
        return !await _repository.ExistsCodeAsync(code, ct);
    }
}
*/

← Volver a la ficha de generador-crud