Ooto
Ooto

Reputation: 1247

Django Form: Validate line by line

I'm creating a form where user input a bunch of email addresses. What I want to do is to validate the emails line by line in TextField.

So what I need to do is to read the input line by line and apply email validator for each line.

How could I do it?

my current code (it's just normal Email form though..)

forms.py

class InputEmailsForm(forms.Form):
    email = forms.EmailField()

    def __init__(self, *args, **kargs):
        super().__init__(*args, **kwargs)
        # override label and error messages here
        ...

Upvotes: 0

Views: 164

Answers (1)

Sam
Sam

Reputation: 2084

Convert your EmailField (which would only accept one address) to a TextField, then write a custom validation function that uses Django's built-in validate_email function to check to ensure that each line contains a valid e-mail address:

from django.core.validators import validate_email
from django.core.exceptions import ValidationError
from django import forms

class InputEmailsForm(forms.Form):
    emails = forms.TextField()

    def clean_emails(self):
        data = self.cleaned_data['emails']

        for line in data.splitlines():
            try validate_email(line):
                pass
            except ValidationError:
                raise forms.ValidationError("The following is not a valid e-mail: {0}".format(line))

        return data

Upvotes: 1

Related Questions