My question is how do I need to validate fields. I have this class (request dto):
public class CompleteGoogleRegistrationRequest
{
public string IdToken { get; set; } = string.Empty;
public string Username { get; set; } = string.Empty;
}
And I need to check Username existance. On which layer should this be checked? On this request validator`s layer or when I create UserEntity and apply entity`s validator to user instance. Maybe neither and check uniqueness only in business logic?
Validator logic:
.MustAsync(async (username, cancellation) =>
{
return await userRepository.GetByUsernameReadonlyAsync(username, cancellation) == null;
})
.WithMessage("This username is already taken.");
Handler logic (business logic):
var existingUser = await userRepository.GetByUsernameReadonlyAsync(userRequest.Username, cancellationToken);
if (existingUser != null)
{
var errorMessage = localization.GetString("Auth.Register.UsernameAlreadyExists");
var errors = new ValidationResult(new[]
{
new ValidationFailure(nameof(userRequest.Username), errorMessage)
});
return Result.Failure<RegisterResponse, ValidationResult>(errors);
}