2

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);
}
New contributor
Dmytro Zhadan is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

1 Answer 1

1
public class CompleteGoogleRegistrationRequestValidator 
    : AbstractValidator<CompleteGoogleRegistrationRequest>
{
    public CompleteGoogleRegistrationRequestValidator()
    {
        RuleFor(x => x.IdToken).NotEmpty();
        RuleFor(x => x.Username)
            .NotEmpty()
            .MinimumLength(3)
            .MaximumLength(30);
    }
}   
``

public async Task<Result<RegisterResponse>> Handle(
    CompleteGoogleRegistrationRequest request,
    CancellationToken cancellationToken)
{
    var existingUser = await userRepository
        .GetByUsernameReadonlyAsync(request.Username, cancellationToken);

    if (existingUser != null)
    {
        var errorMessage = localization.GetString("Auth.Register.UsernameAlreadyExists");

        var errors = new ValidationResult(new[]
        {
            new ValidationFailure(nameof(request.Username), errorMessage)
        });

        return Result.Failure<RegisterResponse>(errors);
    }

    // Continue registration...









try this
}
New contributor
chaghy is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.