@Override public void validate(Object target, Errors errors) { UserModel userModel = (UserModel) target; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", FIELD_MANDATORY); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", FIELD_MANDATORY); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", FIELD_MANDATORY); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", FIELD_MANDATORY); if (isSaveEvent(userModel)) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", FIELD_MANDATORY); } invokeValidator(roleModelValidator, userModel.getRole(), "role", errors); doFurtherValidation(userModel, errors); }
private void doFurtherValidation(UserModel userModel, Errors errors) { if (errors.hasErrors()) { return; } if (isEmailInvalid(userModel.getEmail())) { errors.rejectValue("email", "err.email"); } final String username = userModel.getUsername(); Optional<UserModel> user = userService.findByUsername(username); if (user.isPresent()) { if (isSaveEvent(userModel)) { errors.rejectValue("username", "err.username.exists"); } else if (isUpdateEvent(userModel) && !username.equals(user.get().getUsername())) { errors.rejectValue("username", "err.username.exists"); } } }
private boolean isUpdateEvent(UserModel userModel) { return UPDATE_EVENT.equals(userModel.getSubmitEvent()); }
private boolean isSaveEvent(UserModel userModel) { return SAVE_EVENT.equals(userModel.getSubmitEvent()); }