galaeth-draft/Galaeth.Services/Validators/CreateUserValidator.cs

41 lines
1.7 KiB
C#
Raw Normal View History

2024-11-17 10:31:01 +01:00
using FluentValidation;
using Galaeth.Services.Dtos;
using Galaeth.Services.Interfaces;
using Injectio.Attributes;
namespace Galaeth.Services.Validators;
/// <summary>
/// Validation for <see cref="CreateUserDto"/>.
/// </summary>
[RegisterScoped]
public class CreateUserValidator : AbstractValidator<CreateUserDto>
{
private const int MinimumUsernameLength = 4;
private const int MaximumUsernameLength = 16;
/// <summary>
/// Initializes a new instance of the <see cref="CreateUserValidator"/> class.
/// </summary>
/// <param name="emailDomainBlacklistService">Instance of <see cref="IEmailDomainBlacklistService"/>.</param>
public CreateUserValidator(IEmailDomainBlacklistService emailDomainBlacklistService)
{
RuleFor(dto => dto.Username).NotEmpty().WithMessage("Username must be provided")
.MinimumLength(MinimumUsernameLength)
.WithMessage("Username must be a minimum of " + MinimumUsernameLength + " characters")
.MaximumLength(MaximumUsernameLength)
.WithMessage("Username must be within " + MaximumUsernameLength + " characters")
.Matches(@"^[A-Za-z0-9._-]+$")
.WithMessage("Username can only contain letters, numbers, hyphens, dashes and periods.");
RuleFor(dto => dto.Email).NotEmpty().WithMessage("Email address must be provided")
.EmailAddress().WithMessage("Email address is not a valid email address");
RuleFor(dto => dto.Email).MustAsync(async (email, _) =>
await emailDomainBlacklistService.CheckBlacklist(email) == false)
.WithMessage("Email addresses from this domain cannot be used");
RuleFor(dto => dto.Password).NotEmpty().WithMessage("Password must be provided");
}
}