Create a Feedback Form with Validations such as Required Fields and Email Format

πŸ“Œ 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.py for form definition and validation rules
  • views.py for processing submitted data
  • template for 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=True makes the field compulsory
  • EmailField checks correct email format
  • min_length=10 ensures feedback message is meaningful
  • Textarea is 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, EmailField shows an email error
  • If message is too short, min_length triggers 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

  1. User opens the feedback form
  2. Enters values and submits form
  3. Django checks validation rules automatically
  4. If data is valid, summary is shown
  5. 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

  1. Add phone number field with validation
  2. Set minimum length of subject to 5
  3. Add maximum length to feedback message
  4. Display custom error messages
  5. 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

Django Practice Exercise

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP

Inserting Information from Multiple CheckBox Selection in a Database Table in PHP

programmingempire

princites.com

1 thought on “Create a Feedback Form with Validations such as Required Fields and Email Format

Leave a Reply

Your email address will not be published. Required fields are marked *