72 lines
2.0 KiB
Python
72 lines
2.0 KiB
Python
from dataclasses import dataclass
|
|
from typing import Any, Optional
|
|
|
|
from django.core.handlers.wsgi import WSGIRequest
|
|
from django.http import HttpResponse
|
|
from django.shortcuts import render
|
|
|
|
from project.main.views.demo_view_base import DemoViewBase
|
|
|
|
|
|
@dataclass
|
|
class Validation:
|
|
validated: bool = False
|
|
is_valid: bool = False
|
|
|
|
name: Optional[str] = None
|
|
consent: Optional[bool] = None
|
|
age: Optional[int] = None
|
|
|
|
name_error: Optional[str] = None
|
|
age_error: Optional[str] = None
|
|
consent_error: Optional[str] = None
|
|
|
|
|
|
class FormValidationView(DemoViewBase):
|
|
template_name = "main/form_validation.html"
|
|
active_section = "form-validation"
|
|
title = "Form Validation"
|
|
|
|
def get_context_data(self, **kwargs) -> dict[str, Any]:
|
|
context = super().get_context_data(**kwargs)
|
|
context.update(
|
|
{
|
|
"validation": Validation(),
|
|
}
|
|
)
|
|
return context
|
|
|
|
def post(self, request: WSGIRequest, *args, **kwargs) -> HttpResponse:
|
|
validation = Validation(
|
|
validated=True,
|
|
name=request.POST.get("name", ""),
|
|
age=request.POST.get("age", ""),
|
|
consent=request.POST.get("consent") == "on",
|
|
)
|
|
|
|
if len(validation.name) < 3 or len(validation.name) > 10:
|
|
validation.name_error = "Name must be between 3 and 10 chars long"
|
|
|
|
try:
|
|
age = int(validation.age)
|
|
except ValueError:
|
|
validation.age_error = "Invalid integer"
|
|
else:
|
|
if age < 1 or age > 100:
|
|
validation.age_error = "Age should be between 1 and 100"
|
|
|
|
if not validation.consent:
|
|
validation.consent_error = "You should consent"
|
|
|
|
validation.is_valid = not (
|
|
validation.name_error or validation.age_error or validation.consent_error
|
|
)
|
|
|
|
return render(
|
|
context={
|
|
"validation": validation,
|
|
},
|
|
template_name="main/form_validation_content.html",
|
|
request=request,
|
|
)
|