HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaspringMinor

Validator for a user registration form

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
registrationuservalidatorforform

Problem

In a user registration form, the validator currently checks not only user input, but also whether or not the user exists. This seems like business logic, which in terms of design should be in the service layer in a "save user" type method. On the other hand, it is highly convenient to keep it in the validator.

Should there be a non-input related check in the validator?

public void validate(Object target, Errors errors) {
    User user = (User) target;
    ValidationUtils.rejectIfEmpty(errors, "name", "name.required", "Error msg...");
    ValidationUtils.rejectIfEmpty(errors, "username", "username.required", "Error msg...");
    ValidationUtils.rejectIfEmpty(errors, "password", "password.required", "Error msg...");

    // check if user already exists
    String username = user.getUsername();
    if (username != null && userService.userExists(username)) {
        errors.rejectValue("username", "username.exists", "Username is taken.");
    }
}

Solution

as it probably hits a database, i would call userExists from outside the validate function.
So, registration method first checks the input. Then calls userService.Register(User user, Errors errors). Register detects that username already exists and throws. And validation does not need to know about usernames and that they are unique or non-unique.

Context

StackExchange Code Review Q#59993, answer score: 4

Revisions (0)

No revisions yet.