1

I have a form that otherwise works. Normal validation errors are raised; however, my custom validation function does not raise the validation error. How can I fix this to make it show the custom validation error?

from django import forms


class UserRegistrationForm(forms.Form):
    GENDER=[('male','MALE'), ('female', 'FEMALE')]
    firstName=forms.CharField()
    lastName=forms.CharField()
    email=forms.EmailField()
    gender=forms.CharField(widget=forms.Select(choices=GENDER))
    password=forms.CharField(widget=forms.PasswordInput)
    emp_id=forms.IntegerField(label="Employee ID")
    
    def clean_firstName(self):
        inputFirstName = self.cleaned_data['firstName']
        if len(inputFirstName)>20:
            raise forms.ValidationError('First Name must not exceed 20 characters.')
        return inputFirstName

I also tried inputFirstName = self.cleaned_data.get('firstName')

In either case the form will submit with data that doesn't fit the custom validation.

2
  • 1
    are you checking frm_instance.is_valid() return value before saving the form? Commented Jan 3, 2021 at 18:44
  • 1
    post your view, please. Commented Jan 3, 2021 at 18:45

3 Answers 3

1

In your views.py you need to pass the Form to the request.POST like this.

form = UserRegistrationForm(request.POST)

And on your form variable it will hold the entire form fields and the validation you just created as well the error. pass this to your render context and on your template render

return render(request,'path/to/your/template', {'form': form})

on your template.

{{form.as_ul}}

And you now will be able to show the error on your template.

Sign up to request clarification or add additional context in comments.

Comments

1

Since this is a validator that focusses on a single field, it makes more sense to add a validator to that field:

from django.core.validators import MaxLengthValidator
from django import forms

class UserRegistrationForm(forms.Form):
    firstName = forms.CharField(
        validators=[MaxLengthValidator(20, 'First name must not exceed 20 characters.')]
    )
    # …

If you do not care about the error message, you can make use of the max_length=… parameter [Django-doc]:

from django.core.validators import MaxLengthValidator
from django import forms

class UserRegistrationForm(forms.Form):
    firstName = forms.CharField(max_length=20)
    # …

Comments

0

I think you have forgotten to check the validity of your form before saving it.
Django forms are not raising errors. instead, they give you a method that examines the data and determines whether it is valid or not. The method name is is_valid(). it returns a boolean indicating the result of validation and also collects every valid data into the cleaned_data property of the form instance.
Here I put a working example:

from django import forms

class UserRegistrationForm(forms.Form):
    firstName=forms.CharField()
    def clean_firstName(self):
        inputFirstName = self.cleaned_data['firstName']
        if len(inputFirstName)<3:
            raise forms.ValidationError('First Name must be at least 3 characters.')
        return inputFirstName

frm = UserRegistrationForm({"firstName":"ab"})
frm.is_valid() # result: False
frm.cleaned_data # result: {}
frm = UserRegistrationForm({"firstName":"abc"})
frm.is_valid() # result: True
frm.cleaned_data # result: {'firstName': u'abc'}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.