Below is a step-by-step example of how you can build a “Contact Us” form in Symfony that validates both an email address and a phone number. We’ll use Symfony’s Form & Validator components and a simple regex for phone-number validation.
1. Install Validator (if you haven’t already)
composer require symfony/validator
2. Create a DTO (Data‐Transfer Object) for the form data
src/DTO/ContactData.php
<?php
namespace App\DTO;
use Symfony\Component\Validator\Constraints as Assert;
class ContactData
{
#[Assert\NotBlank(message: 'Email should not be blank.')]
#[Assert\Email(message: 'Please enter a valid email address.')]
private ?string $email = null;
#[Assert\NotBlank(message: 'Phone number should not be blank.')]
// Very simple regex: allows digits, spaces, dashes, parentheses, plus sign
#[Assert\Regex(
pattern: '/^\+?[0-9\-\s\(\)]+$/',
message: 'Please enter a valid phone number.'
)]
private ?string $phone = null;
#[Assert\NotBlank(message: 'Your message cannot be empty.')]
#[Assert\Length(
min: 10,
max: 1000,
minMessage: 'Message must be at least {{ limit }} characters.',
maxMessage: 'Message cannot exceed {{ limit }} characters.'
)]
private ?string $message = null;
// ─── Getters & Setters ─────────────────────────────────────────
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(?string $email): void
{
$this->email = $email;
}
public function getPhone(): ?string
{
return $this->phone;
}
public function setPhone(?string $phone): void
{
$this->phone = $phone;
}
public function getMessage(): ?string
{
return $this->message;
}
public function setMessage(?string $message): void
{
$this->message = $message;
}
}
3. Create the Form Type
src/Form/ContactType.php
<?php
namespace App\Form;
use App\DTO\ContactData;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TelType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ContactType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('email', EmailType::class, [
'label' => 'Your E-mail',
'attr' => ['placeholder' => 'john@example.com'],
])
->add('phone', TelType::class, [
'label' => 'Phone Number',
'attr' => ['placeholder' => '+1 555-1234'],
])
->add('message', TextareaType::class, [
'label' => 'Message',
'attr' => ['rows' => 5],
])
->add('submit', SubmitType::class, [
'label' => 'Send Message',
'attr' => ['class' => 'btn btn-primary mt-3'],
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => ContactData::class,
]);
}
}
4. Create the Controller
src/Controller/ContactController.php
<?php
namespace App\Controller;
use App\DTO\ContactData;
use App\Form\ContactType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class ContactController extends AbstractController
{
#[Route('/contact', name: 'app_contact')]
public function contact(Request $request): Response
{
$contactData = new ContactData();
$form = $this->createForm(ContactType::class, $contactData);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// Here you can send an email, persist to DB, etc.
$this->addFlash('success', 'Your message has been sent!');
// Redirect to avoid form resubmission
return $this->redirectToRoute('app_contact');
}
return $this->render('contact/contact.html.twig', [
'contactForm' => $form->createView(),
]);
}
}
5. Twig Template
templates/contact/contact.html.twig
{% extends 'base.html.twig' %}
{% block title %}Contact Us{% endblock %}
{% block body %}
<h1>Contact Us</h1>
{{ form_start(contactForm) }}
{{ form_row(contactForm.email) }}
{{ form_row(contactForm.phone) }}
{{ form_row(contactForm.message) }}
<button type="submit" class="btn btn-success">{{ contactForm.submit.vars.label }}</button>
{{ form_end(contactForm) }}
{% for label, messages in app.flashes %}
{% for msg in messages %}
<div class="alert alert-{{ label }}">{{ msg }}</div>
{% endfor %}
{% endfor %}
{% endblock %}
How It Works
- DTO + Validator
Our ContactData class uses Symfony’s #[Assert] attributes to declare validation rules (email, regex for phone).
- Form Type
ContactType binds form fields to the DTO, uses built-in EmailType and TelType.
- Controller
Renders the form, handles submission, checks validity, and flashes a success message.
- Twig
Renders fields + errors automatically, displays flash messages.
🎉 With this in place you have a full contact form with both email and phone‐number validation! Feel free to customize the regex or even hook in giggsey/libphonenumber-for-php if you need world-class phone parsing.