Is a mailto URL with slashes still valid?

Viewed 320

I am using a subclassed Django URLField to perform some validation on clicked URLs. I added mailto as one of the supported URLValidator default_validators:

class MyURLField(forms.URLField):
    default_validators = [
        validators.URLValidator(
            schemes=['http', 'https', 'ftp', 'ftps', 'mailto']
        )
    ]


class MyForm(forms.Form):
    url = MyURLField(required=True)


form = MyForm({'url': 'mailto:test@example.com'})
if not form.is_valid():
    raise Exception()

clean_url = form.cleaned_data['url']
print(clean_url)  # this prints 'mailto://test@example.com'

Is a mailto URL still valid with the two extra protocol slashes?

mailto:test@example.com versus mailto://test@example.com (what Django produces)

1 Answers

Django has an EmailField so if you want to store email addresses, or even use them in forms, use these fields because you get the built-in validation and don't have to hack anything like you're going to have to with your approach.

In your models you'd do;

class MyModel(models.Model):

    email = models.EmailField(
        verbose_name=_('Email'),
        max_length=255,
        unique=True,
        db_index=True
    )

In your forms it's very similar;

class MyForm(forms.ModelForm):

    email = forms.EmailField(
        label=_("Email")
    )

And then this becomes a mailto URL when you output it in a template etc;

<a href="mailto:{{ object.email }}">
    {{ object.email }}
</a>
Related