60 lines
1.8 KiB
Python
60 lines
1.8 KiB
Python
from typing import Dict, Any
|
|
import re
|
|
from sqlalchemy.orm import Session
|
|
from models.contact_form import ContactForm
|
|
from schemas.contact_form import ContactFormCreate
|
|
|
|
def create_contact_form(db: Session, contact_form_data: ContactFormCreate) -> ContactForm:
|
|
"""
|
|
Creates a new contact form submission in the database.
|
|
|
|
Args:
|
|
db (Session): The database session.
|
|
contact_form_data (ContactFormCreate): The data for the contact form to create.
|
|
|
|
Returns:
|
|
ContactForm: The newly created contact form object.
|
|
"""
|
|
db_contact_form = ContactForm(**contact_form_data.dict())
|
|
db.add(db_contact_form)
|
|
db.commit()
|
|
db.refresh(db_contact_form)
|
|
return db_contact_form
|
|
|
|
def validate_contact_form_data(contact_form_data: Dict[str, Any]) -> Dict[str, str]:
|
|
"""
|
|
Validates the input data for a contact form submission.
|
|
|
|
Args:
|
|
contact_form_data (Dict[str, Any]): The input data to validate.
|
|
|
|
Returns:
|
|
Dict[str, str]: A dictionary containing error messages for any invalid fields.
|
|
"""
|
|
errors = {}
|
|
|
|
# Check if all required fields are present
|
|
required_fields = ["name", "email", "message"]
|
|
for field in required_fields:
|
|
if field not in contact_form_data or not contact_form_data[field]:
|
|
errors[field] = f"{field.capitalize()} is required."
|
|
|
|
# Check if email is in valid format
|
|
email = contact_form_data.get("email")
|
|
if email and not is_valid_email(email):
|
|
errors["email"] = "Invalid email format."
|
|
|
|
return errors
|
|
|
|
def is_valid_email(email: str) -> bool:
|
|
"""
|
|
Checks if a given email address is in a valid format.
|
|
|
|
Args:
|
|
email (str): The email address to validate.
|
|
|
|
Returns:
|
|
bool: True if the email is valid, False otherwise.
|
|
"""
|
|
email_regex = r'^[\w\.-]+@[\w\.-]+\.\w+$'
|
|
return bool(re.match(email_regex, email)) |