astral-api/Astral.Services/Validators/CreateUserValidator.cs
2024-12-11 20:36:30 +00:00

44 lines
1.9 KiB
C#

// <copyright file="CreateUserValidator.cs" company="alveus.dev">
// Copyright (c) alveus.dev. All rights reserved. Licensed under the MIT License.
// </copyright>
using Astral.Services.Dtos;
using Astral.Services.Interfaces;
using FluentValidation;
using Injectio.Attributes;
namespace Astral.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");
}
}