Search code examples
pythondjangodjango-modelsdjango-validation

RegexValidator in Django Models not validating email correctly


I'm making a django form with an email field and using a RegexValidator and want a specific format of of the email but it seems to be not validating the field correctly

    email = models.EmailField(
        unique=True,
        validators=[
            RegexValidator(
                regex=r"^[2][2][a-zA-Z]{3}\d{3}@[nith.ac.in]*",
                message=
                "Only freshers with college email addresses are authorised.")
        ],
    )

When I am entering the email ending with @nith.ac.in or @nith.acin both are getting accepted while @nith.acin should not get accepted... any sols?


Solution

  • The [nith.ac.in] does not parse literal text, it parses any character in te group, meaning it can end with a sequence of ns, is, nis, etc.

    Your regex should look like:

    email = models.EmailField(
        unique=True,
        validators=[
            RegexValidator(
                regex=r'^[2][2][a-zA-Z]{3}\d{3}@nith[.]ac[.]in$',
                message='Only freshers with college email addresses are authorised.',
            )
        ],
    )