runnerpaul
runnerpaul

Reputation: 7216

Check for duplicate usernames prevents updating user

I have the below Java controller for adding a user:

@GetMapping("/registration")
public String registration(Model model) {
    if (securityService.isAuthenticated()) {
        return "redirect:/";
    }

    model.addAttribute("userForm", new User());

    return "registration";
}

I also have the following validator to prevent duplicate usernames:

if (userService.findByEmail(user.getEmail()) != null) {
    errors.rejectValue("username", "Duplicate.userForm.username");
}

I'm now trying to add a controller to updating an existing user. I created the below to use the same registration form as when creating a user:

@GetMapping("/users/showFormForUpdate")
public String showFormForUpdate(@RequestParam("userId") long theId, Model theModel) {
        
    User theUser = userService.findById(theId);
        
    theModel.addAttribute("userForm", theUser);
        
    return "registration";
}

My problem is that when I attempt to update my duplicate user alert appears if I do not change the username.

This is my code in the registration form that gives the alert:

<div class="form-group">
    <input type="text" th:field="*{username}" class="form-control" placeholder="Username"
                       autofocus="true">
    <span style="color:red" class="has-error" th:if="${#fields.hasErrors('username')}" th:errors="*{username}"></span>
</div>

In summary, when I create a user I want any duplicate usernames to be flagged but if I'm updating the user I don't want this. How can I update my user but maintain the ability to prevent duplicate users? I'm using addAttribute in org.springframework.ui.Model. I know one option would be to use a different form for the update but I would expect there should be a way to do both with one form.

Upvotes: 0

Views: 1261

Answers (1)

Fahim Farook
Fahim Farook

Reputation: 1483

if (userService.findByEmail(user.getEmail()) != null) {
  errors.rejectValue("username", "Duplicate.userForm.username"); }

Avoid the above code level validation and let the database complain if the username is a duplicate. i.e. during registration since the User object does not have a userId, JPA does an insert, and if duplicates present, you will get notified by a DataIntegrityViolationException. During update, JPA does an update since the userId is present, and does not result in a DataIntegrityViolationException.

Upvotes: 1

Related Questions