๐ Introduction
Validation is used to ensure that the user enters correct and complete data.
In this program, we will create a feedback form with:
- required fields
- email format validation
- minimum message length
- error display in the form
This program helps students understand:
- form validation
- required fields
- built-in validators
- error messages in Django forms
๐ฏ Program Statement
๐ Create a feedback form with validations such as required fields and email format.
๐ง Concept
This program uses:
forms.pyfor form definition and validation rulesviews.pyfor processing submitted datatemplatefor displaying form, errors, and submitted summary
โ๏ธ Step 1: Create Form with Validations
๐ File: forms.py
๐น Path:
myproject/myapp/forms.py
๐น Code:
from django import forms
class FeedbackValidationForm(forms.Form):
name = forms.CharField(
label='Enter Your Name',
max_length=100,
required=True
)
email = forms.EmailField(
label='Enter Your Email',
required=True
)
subject = forms.CharField(
label='Enter Subject',
max_length=150,
required=True
)
message = forms.CharField(
label='Enter Feedback',
required=True,
min_length=10,
widget=forms.Textarea(attrs={'rows': 4, 'cols': 40})
)
๐ง Explanation
required=Truemakes the field compulsoryEmailFieldchecks correct email formatmin_length=10ensures feedback message is meaningfulTextareais used for long feedback
โ๏ธ Step 2: Create View
๐ File: views.py
๐น Path:
myproject/myapp/views.py
๐น Code:
from django.shortcuts import render
from .forms import FeedbackValidationForm
def feedback_validation(request):
submitted_data = None
if request.method == 'POST':
form = FeedbackValidationForm(request.POST)
if form.is_valid():
submitted_data = {
'name': form.cleaned_data['name'],
'email': form.cleaned_data['email'],
'subject': form.cleaned_data['subject'],
'message': form.cleaned_data['message']
}
else:
form = FeedbackValidationForm()
return render(request, 'feedback_validation.html', {
'form': form,
'data': submitted_data
})
๐ง Explanation
- Blank form is shown on first load
- On POST submission, Django validates the fields automatically
- If the form is valid, submitted values are shown
- If invalid, errors are displayed in the template
โ๏ธ Step 3: URL Mapping
๐ File: urls.py
๐น Path:
myproject/myproject/urls.py
๐น Code:
from django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('feedback-validation/', views.feedback_validation, name='feedback_validation'),
]
โ๏ธ Step 4: Create Template
๐ File: feedback_validation.html
๐น Path:
myproject/templates/feedback_validation.html
๐น Code:
<!DOCTYPE html>
<html>
<head>
<title>Feedback Form with Validation</title>
</head>
<body>
<h1>Feedback Form with Validation</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit Feedback</button>
</form>
<hr>
{% if data %}
<h2>Submitted Feedback Summary</h2>
<p><strong>Name:</strong> {{ data.name }}</p>
<p><strong>Email:</strong> {{ data.email }}</p>
<p><strong>Subject:</strong> {{ data.subject }}</p>
<p><strong>Message:</strong> {{ data.message }}</p>
{% endif %}
</body>
</html>
๐ง Explanation
- If any field is empty, Django shows validation error automatically
- If email format is invalid,
EmailFieldshows an email error - If message is too short,
min_lengthtriggers an error
โ๏ธ Step 5: Run Server
python manage.py runserver
๐ Step 6: Output
Open:
๐ http://127.0.0.1:8000/feedback-validation/
โ Valid Input Example:
- Name: Juhi
- Email: juhi@gmail.com
- Subject: Website Feedback
- Message: This website is very helpful for students.
โ Output:
Submitted Feedback Summary Name: Juhi Email: juhi@gmail.com Subject: Website Feedback Message: This website is very helpful for students.
โ Invalid Input Example 1:
- Email:
abc
Output:
Enter a valid email address.
โ Invalid Input Example 2:
- Message:
Good
Output:
Ensure this value has at least 10 characters.
โ Invalid Input Example 3:
- Leave name empty
Output:
This field is required.
๐ง How It Works
- User opens the feedback form
- Enters values and submits form
- Django checks validation rules automatically
- If data is valid, summary is shown
- If data is invalid, error messages appear near fields
๐ฅ Key Concepts
Required Fields
required=True
Ensures the field cannot be left empty.
Email Validation
forms.EmailField()
Checks that the entered email is in valid format.
Minimum Length
min_length=10
Ensures the message is not too short.
Built-in Error Display
{{ form.as_p }}
Automatically displays field errors in the template.
โ ๏ธ Common Errors
โ Forgot required=True
Then empty input may not be blocked as expected.
โ Used CharField for email
This will not validate email format automatically.
โ Forgot min_length
Short messages like โokโ will be accepted.
โ Forgot CSRF token
POST form will fail with security error.
โ Imported wrong form in views.py
Use:
from .forms import FeedbackValidationForm
๐งช Practice Questions
- Add phone number field with validation
- Set minimum length of subject to 5
- Add maximum length to feedback message
- Display custom error messages
- Add optional city field
๐ค Viva Questions & Answers
1. What is form validation in Django?
Form validation is the process of checking whether the user input is correct, complete, and acceptable before processing it.
2. What is the use of required=True?
It makes the form field compulsory. If the user leaves it empty, Django shows an error.
3. Why is EmailField used instead of CharField?
EmailField automatically checks that the entered value follows a valid email format. CharField does not do this.
4. What is min_length in Django forms?
min_length defines the minimum number of characters required in a field. It helps reject very short input.
5. What happens if a form is invalid?
The form is not processed, and Django displays error messages for the fields that failed validation.
6. Where are validation rules usually written?
Validation rules are usually written in forms.py while defining the fields.
7. Does Django automatically show form errors?
Yes, when using {{ form.as_p }} or similar rendering methods, field errors are displayed automatically.
8. Why are validations important in forms?
Validations ensure data quality, prevent incorrect input, and improve reliability of the application.
9. Can we add more advanced validation later?
Yes, Django supports custom validation methods, including clean() and field-specific cleaning methods.
๐ Next Post: Create an Age Validation Form that Checks Eligibility (age โฅ 18)
๐ Back to List: Django Programs (60 Questions with Solutions)
Further Reading
Introduction to Django Framework and its Features
Examples of Array Functions in PHP
Registration Form Using PDO in PHP
Inserting Information from Multiple CheckBox Selection in a Database Table in PHP
- Angular
- ASP.NET
- C
- C#
- C++
- CSS
- Dot Net Framework
- HTML
- IoT
- Java
- JavaScript
- Kotlin
- PHP
- Power Bi
- Python
- Scratch 3.0
- TypeScript
- VB.NET
