Skip to content

JSON serializer & custom validation

The generator detects which serializers are available and produces the corresponding converters:

SerializerGenerated converterRegistration
System.Text.JsonPatchFieldJsonConverterFactoryoptions.Converters.Add(new PatchFieldJsonConverterFactory())
Newtonsoft.JsonPatchFieldNewtonsoftConvertersettings.Converters.Add(new PatchFieldNewtonsoftConverter())

Both are generated if both packages are referenced. No converter is auto-registered — you choose which one to use, or write your own.

Implement IDtoValidator<T> and point to it from the attribute:

public class MyCreateValidator : IDtoValidator<CreatePlayerRequest>
{
public DtoValidationResult Validate(CreatePlayerRequest instance)
{
var result = new DtoValidationResult();
if (instance.Name.HasValue && instance.Name.Value.Length < 3)
result.AddError("name", "must be at least 3 characters.");
return result;
}
}
[CreateDto(Validator = typeof(MyCreateValidator))]
public class Player { ... }

When a validator is set, Validate() delegates entirely to it — the default generated rules are replaced.

When FluentValidation is installed, the generator additionally produces:

  • FluentDtoValidator<T> — base class bridging FluentValidation with IDtoValidator<T>
  • {RequestName}CreateBaseValidator — contains the generated required/null rules
  • {RequestName}UpdateBaseValidator — contains the generated null rules

Inherit to extend:

public class MyCreateValidator : CreatePlayerRequestCreateBaseValidator
{
public MyCreateValidator()
{
RuleFor(x => x.Name)
.Must(f => !f.HasValue || f.Value.Length >= 3)
.WithMessage("Name must be at least 3 characters.");
}
}
[CreateDto(Validator = typeof(MyCreateValidator))]
public class Player { ... }

Or start from scratch:

public class MyCreateValidator : FluentDtoValidator<CreatePlayerRequest>
{
public MyCreateValidator()
{
// your rules only
}
}
  • .NET 6+ (or .NET Framework with SDK-style projects and System.Text.Json NuGet)
  • required keyword needs C# 11 / .NET 7+ (optional — without it all properties are optional in Create)

MIT