Skip to content

validate.Email accepts a leading/trailing hyphen in the last domain label #3072

Open

Description

@lequangdung2005

validate.Email is currently allowing domain names that start or end with a hyphen to bypass in certain cases such as “user@example.-com”, “user@example.com-”. We believe domain labels must not start or end with a hyphen (RFC 5321 §4.1.2), and Email already rejects this for the other labels, e.g. “user@ex-.com”

After some investigation, the cause is how Email.DOMAIN_REGEX matches the last domain label, which allows a hyphen to appear anywhere. To fix this, we can wrap that alternative in two lookarounds so the label can neither start nor end with a hyphen: (?!-) at the start and (?<!-) at the end. Django's URLValidator uses the same approach for its TLD regex.

Reproducible Tests

from marshmallow import validate

email = validate.Email()
email("user@ex-.com")       # ValidationError, as expected
email("user@example.-com")  # passes
email("user@example.com-")  # passes
email("user@例え.-テスト")   # passes

Proposed fixes

     r"(?:[A-Z" + _UNICODE_LETTERS + r"]{2,6}"
-    r"|[A-Z0-9" + _UNICODE_LETTERS + r"-]{2,})\Z"
+    r"|(?!-)[A-Z0-9" + _UNICODE_LETTERS + r"-]{2,}(?<!-))\Z"

Version

marshmallow 4.3.1 (same on dev at 1c63bda), Python 3.12


AI usage disclosure

This bug was detected by our bug detection tool, which is built on PatchGuru. Two authors carefully reviewed all warnings raised by the tool, and we report only warnings which are likely real bugs. The report and reproduction tests were manually drafted by authors based on evidence provided by the tool and independently verified by two authors.

Activity

  1. X6M-Work commented on Nov 7, 2026

    @X6M-Work
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions