diff --git a/app/main/forms.py b/app/main/forms.py index 3b05c7b9e..4b1deece3 100644 --- a/app/main/forms.py +++ b/app/main/forms.py @@ -1535,6 +1535,12 @@ class ChangeEmailForm(StripWhitespaceForm): email_address = email_address() def validate_email_address(self, field): + # The validate_email_func can be used to call API to check if the email address is already in + # use. We don't want to run that check for invalid email addresses, since that will cause an error. + # If there are any other validation errors on the email_address, we should skip this check. + if self.email_address.errors: + return + is_valid = self.validate_email_func(field.data) if is_valid: raise ValidationError("The email address is already in use") diff --git a/tests/app/main/views/test_user_profile.py b/tests/app/main/views/test_user_profile.py index c9dfcef7b..0368f8fca 100644 --- a/tests/app/main/views/test_user_profile.py +++ b/tests/app/main/views/test_user_profile.py @@ -74,7 +74,6 @@ def test_should_show_name_page( def test_should_redirect_after_name_change( client_request, mock_update_user_attribute, - mock_email_is_not_already_in_use ): client_request.post( 'main.user_profile_name', @@ -109,6 +108,8 @@ def test_should_redirect_after_email_change( ) ) + assert mock_email_is_not_already_in_use.called + @pytest.mark.parametrize('email_address,error_message', [ ('me@example.com', 'Enter a public sector email address or find out who can use Notify'), @@ -128,6 +129,8 @@ def test_should_show_errors_if_new_email_address_does_not_validate( ) assert normalize_spaces(page.find('span', class_='govuk-error-message').text) == f'Error: {error_message}' + # We only call API to check if the email address is already in use if there are no other errors + assert not mock_email_is_not_already_in_use.called def test_should_show_authenticate_after_email_change(