English
Validation
Step 1. Validation rules as classes
Why. Every command that comes from a client must be checked before anything else happens: a user name of the right length and characters, an email that looks like one, a message body of at most 4000 characters. Writing these checks as if statements at the top of each service method mixes them with the business logic and makes them hard to see as a whole.
FluentValidation describes the rules of one command in one small class:
cs
RuleFor(c => c.Email).NotEmpty().EmailAddress().MaximumLength(256);The rules read like a specification, can be tested on their own, and report every broken rule at once, per field — exactly what a registration form needs to show its errors next to the fields.
Do. Add the package to Chatex.Core, together with Microsoft.Extensions.Configuration.Abstractions, which AddCore will need at the end of this topic:
powershell
dotnet add Source/Chatex.Core package FluentValidationpowershell
dotnet add Source/Chatex.Core package Microsoft.Extensions.Configuration.Abstractionsxml
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\Chatex.Data\Chatex.Data.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="FluentValidation" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" />
</ItemGroup>
</Project>Step 2. From validation result to Error
Why. FluentValidation returns its own ValidationResult with a list of failures. The services speak Result and Error, so a small bridge turns failures into one validation error with per-field details. The field names must match what the client sees in JSON: the C# property UserName is userName in the request body.
Do.
cs
using System.Text.RegularExpressions;
using FluentValidation;
namespace Chatex.Core.Common;
internal static class ValidationExtensions
{
/// <summary>Runs the validator; returns null when <paramref name="instance"/> is valid.</summary>
public static async Task<Error?> ValidateToErrorAsync<T>(
this IValidator<T> validator, T instance, CancellationToken cancellationToken)
{
var result = await validator.ValidateAsync(instance, cancellationToken);
if (result.IsValid)
{
return null;
}
return Error.Validation("validation_failed", "One or more fields are invalid.") with
{
Details = result.Errors
.GroupBy(e => CamelCase(e.PropertyName))
.ToDictionary(g => g.Key, g => g.Select(e => e.ErrorMessage).ToArray()),
};
}
/// <summary>Field names as clients see them in JSON: <c>UserName</c> becomes <c>userName</c>.</summary>
private static string CamelCase(string name) =>
name.Length == 0 ? name : char.ToLowerInvariant(name[0]) + name[1..];
/// <summary>
/// A Telegram-style handle: starts with a letter, then letters, digits or underscores. Null passes;
/// combine with NotEmpty when the handle is required.
/// </summary>
public static IRuleBuilderOptions<T, TProperty> Handle<T, TProperty>(
this IRuleBuilder<T, TProperty> rule, int minLength, int maxLength)
{
var pattern = new Regex($"^[A-Za-z][A-Za-z0-9_]{{{minLength - 1},{maxLength - 1}}}$", RegexOptions.CultureInvariant);
return rule
.Must(value => value is not string text || pattern.IsMatch(text))
.WithMessage($"Use {minLength}-{maxLength} letters, digits or underscores, starting with a letter.");
}
}ValidateToErrorAsyncis an extension method onIValidator<T>. It returnsnullwhen the command is valid, so a service can write:csif (await validator.ValidateToErrorAsync(command, cancellationToken) is { } invalid) { return invalid; }The pattern
is { } invalidmeans "is notnull, and call itinvalid".GroupBy+ToDictionarycollect all messages of one field into an array:{ "password": ["...", "..."] }.with { Details = ... }creates a copy of the error record with the details filled in — records support non-destructive mutation.Handleis a custom rule for the@handlesof users and chats: a letter first, then letters, digits or underscores, with a given length. It extends FluentValidation'sIRuleBuilder, so it chains like a built-in rule:RuleFor(c => c.UserName).NotEmpty().Handle(3, 32).nullpasses, so the same rule serves optional handles (a private chat has none).The regular expression is built once per rule with
RegexOptions.CultureInvariant; the doubled braces inside the interpolated string produce the single braces of the quantifier,{2,31}forHandle(3, 32).
The class is internal: only the services of this project use it.
Step 3. Identity's errors
Why. Some rules are checked by ASP.NET Core Identity, not by our validators: the password rules (length, digits), the allowed characters of a user name, a duplicate user name. Identity reports them as a list of IdentityError with codes such as PasswordTooShort or DuplicateUserName. They must reach the client in the same shape as our own validation errors.
Do.
cs
using Microsoft.AspNetCore.Identity;
namespace Chatex.Core.Common;
internal static class IdentityErrors
{
/// <summary>Turns Identity's errors into one validation error, grouped under the field they concern.</summary>
public static Error ToValidationError(IEnumerable<IdentityError> errors)
{
var details = errors
.GroupBy(e => FieldOf(e.Code))
.ToDictionary(g => g.Key, g => g.Select(e => e.Description).ToArray());
return Error.Validation("validation_failed", "One or more fields are invalid.") with { Details = details };
}
private static string FieldOf(string code) => code switch
{
_ when code.StartsWith("Password", StringComparison.Ordinal) => "password",
_ when code.Contains("UserName", StringComparison.Ordinal) => "userName",
_ when code.Contains("Email", StringComparison.Ordinal) => "email",
_ => "",
};
}FieldOf guesses the field from the error code with a switch expression whose arms are guards only (_ when ...): codes that start with Password belong to password, and so on. Errors that fit no field land under the empty key "", the conventional place for errors of the whole object.
The using Microsoft.AspNetCore.Identity; works without a new package: Chatex.Core references Chatex.Data, which references the Identity package, and package references flow on to the projects that reference a project.
Check
dotnet build succeeds with zero warnings.