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.
CodePudding user response:
I think, you can do it manually, by making a list of special characters and punctuation marks, and do iteration for every character of name
field, an 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 contains 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