feat: implement contact form submission endpoint with validation

This commit is contained in:
Backend IM Bot 2025-04-30 07:52:42 +00:00
parent e3f46073ef
commit 3af068704d
2 changed files with 23 additions and 22 deletions

View File

@ -15,29 +15,24 @@ async def submit_contact_form(
Submit a new contact form with name, email, and message.
All fields are required and email must be in valid format.
"""
# Validate the form data
errors = validate_contact_form_data({
"name": contact_form.name,
"email": contact_form.email,
"message": contact_form.message
})
# Validate the contact form data
validation_errors = validate_contact_form_data(contact_form.dict())
# If there are validation errors, return 400 with error details
if errors:
# If there are validation errors, return a 400 response with the errors
if validation_errors:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=errors
detail=validation_errors
)
# Create the contact form in the database
created_form = create_contact_form(db=db, contact_form_data=contact_form)
# Create the contact form submission
new_contact_form = create_contact_form(db=db, contact_form_data=contact_form)
return {
"status": "success",
"message": "Contact form submitted successfully",
"data": {
"id": created_form.id,
"name": created_form.name,
"email": created_form.email
}
"id": new_contact_form.id,
"name": new_contact_form.name,
"email": new_contact_form.email,
"message": new_contact_form.message,
"created_at": new_contact_form.created_at,
"status": "success"
}

View File

@ -45,21 +45,27 @@ def validate_contact_form_data(data: Dict[str, Any]) -> Dict[str, str]:
"""
errors = {}
# Check required fields
# Check required fields with specific error messages
if not data.get("name"):
errors["name"] = "Name is required"
elif not isinstance(data.get("name"), str) or len(data.get("name").strip()) == 0:
errors["name"] = "Name must be a non-empty string"
# Email validation with detailed error handling
if not data.get("email"):
errors["email"] = "Email is required"
elif data.get("email"):
else:
try:
# Validate email format using email_validator package
validate_email(data["email"])
validate_email(data["email"], check_deliverability=True)
except EmailNotValidError as e:
errors["email"] = f"Email validation failed: {str(e)}"
errors["email"] = f"Invalid email format: {str(e)}"
# Message validation
if not data.get("message"):
errors["message"] = "Message is required"
elif not isinstance(data.get("message"), str) or len(data.get("message").strip()) == 0:
errors["message"] = "Message must be a non-empty string"
return errors