ronnythedev/dotnet-clean-architecture-skills/11-dotnet-fluent-validation

Claude Code and agent skill by ronnythedev/dotnet-clean-architecture-skills

Trust tier 2
  • community
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

Generates FluentValidation validators for commands and queries. Includes common validation rules, custom validators, async validation, and integration with MediatR pipeline behaviors.

Install

npx vskill@latest install ronnythedev/dotnet-clean-architecture-skills/11-dotnet-fluent-validation

SKILL.md

FluentValidation Rules Generator

Overview

FluentValidation provides a fluent interface for building strongly-typed validation rules:

  • Declarative rules - Readable, maintainable validation logic
  • Separation of concerns - Validation separate from domain
  • Integration with MediatR - Automatic validation via pipeline behavior
  • Custom validators - Reusable validation components

Quick Reference

Validator TypePurposeExample
Built-inCommon validationsNotEmpty(), MaximumLength()
CustomReusable rulesMust(BeValidEmail)
AsyncDatabase checksMustAsync(BeUniqueEmail)
ChildNested objectsSetValidator(new AddressValidator())
CollectionList itemsRuleForEach(x => x.Items)

Validator Structure

/Application/{Feature}/
├── Create{Entity}/
│ ├── Create{Entity}Command.cs
│ └── Create{Entity}CommandValidator.cs # Or inline in Command.cs
├── Update{Entity}/
│ └── Update{Entity}Command.cs # Validator inline
└── Validators/
├── EmailValidator.cs # Reusable validators
└── PhoneNumberValidator.cs

Template: Basic Command Validator

csharp
// src/{name}.application/{Feature}/Create{Entity}/Create{Entity}CommandValidator.cs
using FluentValidation;
namespace {name}.application.{feature}.Create{Entity};
public sealed class Create{Entity}CommandValidator : AbstractValidator<Create{Entity}Command>
{
public Create{Entity}CommandValidator()
{
// ═══════════════════════════════════════════════════════════════
// STRING VALIDATIONS
// ═══════════════════════════════════════════════════════════════
RuleFor(x => x.Name)
.NotEmpty()
.WithMessage("{Entity} name is required")
.MaximumLength(100)
.WithMessage("{Entity} name must not exceed 100 characters")
.MinimumLength(2)
.WithMessage("{Entity} name must be at least 2 characters");
RuleFor(x => x.Description)
.MaximumLength(500)
.WithMessage("Description must not exceed 500 characters")
.When(x => !string.IsNullOrEmpty(x.Description));
// ═══════════════════════════════════════════════════════════════
// GUID VALIDATIONS
// ═══════════════════════════════════════════════════════════════
RuleFor(x => x.OrganizationId)
.NotEmpty()
.WithMessage("Organization ID is required")
.NotEqual(Guid.Empty)
.WithMessage("Organization ID cannot be empty GUID");
// ═══════════════════════════════════════════════════════════════
// OPTIONAL FOREIGN KEY
// ═══════════════════════════════════════════════════════════════
RuleFor(x => x.ParentId)
.NotEqual(Guid.Empty)
.WithMessage("Parent ID cannot be empty GUID")
.When(x => x.ParentId.HasValue);
}
}

Template: Inline Validator (Preferred Pattern)

csharp
// src/{name}.application/{Feature}/Create{Entity}/Create{Entity}Command.cs
using FluentValidation;
using {name}.application.abstractions.messaging;
using {name}.domain.abstractions;
namespace {name}.application.{feature}.Create{Entity};
// ═══════════════════════════════════════════════════════════════
// COMMAND
// ═══════════════════════════════════════════════════════════════
public sealed record Create{Entity}Command(
string Name,
string? Description,
Guid OrganizationId,
string Email,
decimal Amount,
List<CreateItemRequest> Items) : ICommand<Guid>;
public sealed class CreateItemRequest
{
public required string Name { get; init; }
public int Quantity { get; init; }
}
// ═══════════════════════════════════════════════════════════════
// VALIDATOR (internal, same file)
// ═══════════════════════════════════════════════════════════════
internal sealed class Create{Entity}CommandValidator : AbstractValidator<Create{Entity}Command>
{
public Create{Entity}CommandValidator()
{
RuleFor(x => x.Name)
.NotEmpty()
.MaximumLength(100);
RuleFor(x => x.Email)
.NotEmpty()
.EmailAddress()
.WithMessage("A valid email address is required");
RuleFor(x => x.Amount)
.GreaterThan(0)
.WithMessage("Amount must be positive")
.LessThanOrEqualTo(1_000_000)
.WithMessage("Amount cannot exceed 1,000,000");
RuleFor(x => x.Items)
.NotEmpty()
.WithMessage("At least one item is required")
.Must(items => items.Count <= 100)
.WithMessage("Cannot have more than 100 items");
RuleForEach(x => x.Items)
.ChildRules(item =>
{
item.RuleFor(i => i.Name)
.NotEmpty()
.MaximumLength(200);
item.RuleFor(i => i.Quantity)
.GreaterThan(0)
.LessThanOrEqualTo(10000);
});
}
}
// ═══════════════════════════════════════════════════════════════
// HANDLER
// ═══════════════════════════════════════════════════════════════
internal sealed class Create{Entity}CommandHandler
: ICommandHandler<Create{Entity}Command, Guid>
{
// ... implementation
}

Template: Async Validator with Database Check

csharp
// src/{name}.application/{Feature}/Create{Entity}/Create{Entity}CommandValidator.cs
using FluentValidation;
using {name}.domain.{aggregate};
namespace {name}.application.{feature}.Create{Entity};
internal sealed class Create{Entity}CommandValidator : AbstractValidator<Create{Entity}Command>
{
private readonly I{Entity}Repository _{entity}Repository;
private readonly IOrganizationRepository _organizationRepository;
public Create{Entity}CommandValidator(
I{Entity}Repository {entity}Repository,
IOrganizationRepository organizationRepository)
{
_{entity}Repository = {entity}Repository;
_organizationRepository = organizationRepository;
// Sync validations first (fast)
RuleFor(x => x.Name)
.NotEmpty()
.MaximumLength(100);
RuleFor(x => x.OrganizationId)
.NotEmpty();
// Async validations (database calls)
RuleFor(x => x.Name)
.MustAsync(BeUniqueName)
.WithMessage("A {entity} with this name already exists");
RuleFor(x => x.OrganizationId)
.MustAsync(OrganizationExists)
.WithMessage("Organization does not exist");
}
private async Task<bool> BeUniqueName(string name, CancellationToken ct)
{
var existing = await _{entity}Repository.GetByNameAsync(name, ct);
return existing is null;
}
private async Task<bool> OrganizationExists(Guid organizationId, CancellationToken ct)
{
return await _organizationRepository.ExistsAsync(organizationId, ct);
}
}

Note: Prefer doing existence checks in the Handler rather than Validator for better separation of concerns and testability. Use async validation sparingly.


Template: Reusable Custom Validator

csharp
// src/{name}.application/Validators/EmailValidator.cs
using FluentValidation;
using FluentValidation.Validators;
namespace {name}.application.validators;
/// <summary>
/// Validates email format with stricter rules than built-in EmailAddress
/// </summary>
public sealed class StrictEmailValidator<T> : PropertyValidator<T, string>
{
public override string Name => "StrictEmailValidator";
public override bool IsValid(ValidationContext<T> context, string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return true; // Let NotEmpty handle null/empty
}
// Stricter email validation
value = value.Trim().ToLowerInvariant();
if (value.Length > 254)
return false;
var atIndex = value.IndexOf('@');
if (atIndex <= 0)
return false;
var dotIndex = value.LastIndexOf('.');
if (dotIndex <= atIndex + 1)
return false;
if (dotIndex >= value.Length - 1)
return false;
// Check for common invalid patterns
if (value.Contains("..") || value.Contains(".@") || value.Contains("@."))
return false;
return true;
}
protected override string GetDefaultMessageTemplate(string errorCode)
=> "{PropertyName} must be a valid email address";
}
// Extension method for fluent usage
public static class ValidatorExtensions
{
public static IRuleBuilderOptions<T, string> StrictEmail<T>(
this IRuleBuilder<T, string> ruleBuilder)
{
return ruleBuilder.SetValidator(new StrictEmailValidator<T>());
}
}
Using Custom Validator
csharp
public sealed class CreateUserCommandValidator : AbstractValidator<CreateUserCommand>
{
public CreateUserCommandValidator()
{
RuleFor(x => x.Email)
.NotEmpty()
.StrictEmail(); // Custom validator
}
}

Template: Nested Object Validator

csharp
// src/{name}.application/Validators/AddressValidator.cs
using FluentValidation;
namespace {name}.application.validators;
public sealed class AddressValidator : AbstractValidator<AddressRequest>
{
public AddressValidator()
{
RuleFor(x => x.Street)
.NotEmpty()
.MaximumLength(200);
RuleFor(x => x.City)
.NotEmpty()
.MaximumLength(100);
RuleFor(x => x.State)
.NotEmpty()
.MaximumLength(50);
RuleFor(x => x.ZipCode)
.NotEmpty()
.Matches(@"^\d{5}(-\d{4})?$")
.WithMessage("Invalid ZIP code format");
RuleFor(x => x.Country)
.NotEmpty()
.MaximumLength(100);
}
}
// Using nested validator
public sealed class CreateCustomerCommandValidator : AbstractValidator<CreateCustomerCommand>
{
public CreateCustomerCommandValidator()
{
RuleFor(x => x.Name)
.NotEmpty()
.MaximumLength(100);
// Nested object validation
RuleFor(x => x.BillingAddress)
.NotNull()
.WithMessage("Billing address is required")
.SetValidator(new AddressValidator());
// Optional nested object
RuleFor(x => x.ShippingAddress)
.SetValidator(new AddressValidator()!)
.When(x => x.ShippingAddress is not null);
}
}

Template: Collection Validator

csharp
// src/{name}.application/{Feature}/CreateOrder/CreateOrderCommandValidator.cs
using FluentValidation;
namespace {name}.application.orders.createorder;
public sealed class CreateOrderCommandValidator : AbstractValidator<CreateOrderCommand>
{
public CreateOrderCommandValidator()
{
// Collection must have items
RuleFor(x => x.Items)
.NotEmpty()
.WithMessage("Order must contain at least one item")
.Must(items => items.Count <= 50)
.WithMessage("Order cannot contain more than 50 items");
// Validate each item in collection
RuleForEach(x => x.Items)
.ChildRules(item =>
{
item.RuleFor(i => i.ProductId)
.NotEmpty();
item.RuleFor(i => i.Quantity)
.GreaterThan(0)
.LessThanOrEqualTo(1000);
item.RuleFor(i => i.UnitPrice)
.GreaterThan(0);
});
// Cross-item validation
RuleFor(x => x.Items)
.Must(HaveUniqueProducts)
.WithMessage("Order cannot contain duplicate products");

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
64
Repository forks
11
7-day trend score
21

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/ronnythedev/dotnet-clean-architecture-skills/11-dotnet-fluent-validation/badge)](https://verified-skill.com/skills/ronnythedev/dotnet-clean-architecture-skills/11-dotnet-fluent-validation)

Something wrong with this skill or its page? Tell us.