Django: cleaned_data for special characters and punctuation marks

Question:

I want to validate the Name field in my form.

Now I have in my forms.py:

 def clean_name(self):
        name = self.cleaned_data['name']
        if re.search(r'd', name):
            raise ValidationError('The name must not have numbers')
        if re.search(r's', name):
            raise ValidationError('The name must not have spaces')
        return name

But I also want to create validation for special characters and punctuation marks.

I have tried some ways with [[:punct:]], but this returns an error to me, and I guess that this doesn’t work with Python or another way of using it is needed.

Is there any way to do this, I need help.

Asked By: Elliot13

||

Answers:

I think you can do it manually by making a list of special characters and punctuation marks and iterating each character of name field, as shown in the example here:

def clean_name(self):
    name = self.cleaned_data['name']
    special_puncs = ['!', '@', '#', '$', '%', '&', '*', '(', ')'] # you can also include more chars and puncs
    for i in name:
        if i in special_puncs:
            raise ValidationError(
                'Name cannot contain special chars and punctuations.')

    if re.search(r'd', name):
        raise ValidationError('The name must not have numbers')
    if re.search(r's', name):
        raise ValidationError('The name must not have spaces')
    return name
Answered By: Sunderam Dubey