3. Registration form
You will give a form a dependency, check a value against your data, compare two fields and require a ticked box.
Try it: Mezzio ยท laminas-mvc
Assumes you have done chapter 0 and chapter 2.
<?php
declare(strict_types=1);
namespace App\Forms\Register;
use App\Forms\Password\AbstractNewPasswordForm;
use Laminas\Filter\StringTrim;
use Laminas\Form\Element\Checkbox;
use Laminas\Form\Element\Email;
use Laminas\Form\Element\Submit;
use Laminas\Form\Element\Text;
use Laminas\InputFilter\InputFilterProviderInterface;
use Laminas\Validator\AbstractValidator;
use Laminas\Validator\InArray;
use Laminas\Validator\NotEmpty;
use Laminas\Validator\StringLength;
use LogicException;
use Override;
/**
* Collects the details for a new account
*
* It needs a service, so register RegisterFormFactory with the form element manager.
*
* @api
*
* @extends AbstractNewPasswordForm<array<string, mixed>>
*/
final class RegisterForm extends AbstractNewPasswordForm implements InputFilterProviderInterface
{
private const string EMAIL_FORMAT = 'Enter an email address in the format name@example.com';
public function __construct(
private readonly EmailAvailabilityInterface $emails,
) {
parent::__construct();
}
/** @throws LogicException If the email element has been replaced by another type. */
#[Override]
public function getInputFilterSpecification(): array
{
return [
'name' => [
'required' => true,
'filters' => [['name' => StringTrim::class]],
'validators' => [
$this->notEmpty('Enter your name'),
[
'name' => StringLength::class,
'options' => [
'max' => 100,
'messages' => [StringLength::TOO_LONG => 'Your name must be 100 characters or fewer'],
],
],
],
],
// The Email element already trims and checks the format, so these rules are added to its own
'email' => [
'required' => true,
'validators' => [
// A high priority puts this ahead of the element's format validator
[...$this->notEmpty(self::EMAIL_FORMAT), 'priority' => 100],
new EmailAvailableValidator($this->emails, $this->email()->getEmailValidator()),
],
],
// An unticked box submits "0", which the Checkbox element accepts. Only "1" means agreement
'terms' => [
'required' => true,
'error_message' => 'Agree to the terms to create an account',
'validators' => [['name' => InArray::class, 'options' => ['haystack' => ['1']]]],
],
];
}
#[Override]
public function init(): void
{
parent::init();
$this->add([
'name' => 'name',
'type' => Text::class,
'options' => ['label' => 'Your name'],
'attributes' => ['id' => 'name', 'required' => true, 'maxlength' => 100, 'autocomplete' => 'name'],
]);
$this->add([
'name' => 'email',
'type' => Email::class,
'options' => ['label' => 'Email address'],
'attributes' => [
'id' => 'email',
'required' => true,
'autocomplete' => 'username',
'autocapitalize' => 'none',
'spellcheck' => 'false',
],
]);
$format = $this->email()->getEmailValidator();
if ($format instanceof AbstractValidator) {
$format->setMessage(self::EMAIL_FORMAT);
}
$this->addNewPasswordFields('Password', 'Type your password again');
$this->add([
'name' => 'terms',
'type' => Checkbox::class,
'options' => ['label' => 'I agree to the terms of service'],
'attributes' => ['id' => 'terms', 'required' => true],
]);
$this->add([
'name' => 'register',
'type' => Submit::class,
'attributes' => ['value' => 'Create account'],
]);
}
/** @throws LogicException If the email element has been replaced by another type. */
private function email(): Email
{
$element = $this->get('email');
return $element instanceof Email ? $element : throw new LogicException('The email element is missing');
}
/** @return array{name: class-string<NotEmpty>, break_chain_on_failure: true, options: array{messages: array<string, string>}} */
private function notEmpty(string $message): array
{
return [
'name' => NotEmpty::class,
'break_chain_on_failure' => true,
'options' => ['messages' => [NotEmpty::IS_EMPTY => $message]],
];
}
}
The password rules live in an input filter of their own, because chapter 5 uses them again. A base class adds the two fields and attaches it:
<?php
declare(strict_types=1);
namespace App\Forms\Password;
use Laminas\InputFilter\InputFilter;
use Laminas\Validator\Identical;
use Laminas\Validator\NotEmpty;
use Laminas\Validator\StringLength;
use Override;
/**
* The rules for choosing a password, shared by every form that sets one
*
* Passwords are never filtered: every character counts. Fetch the filter from the input filter
* plugin manager, which calls init().
*
* @api
*
* @extends InputFilter<array<string, mixed>>
*/
final class NewPasswordInputFilter extends InputFilter
{
public const int MIN = 15;
public const int MAX = 128;
private const string FIELD_TO_MATCH = 'password';
#[Override]
public function init(): void
{
$this->add(
[
'required' => true,
'validators' => [
$this->notEmpty('Enter a password'),
[
'name' => StringLength::class,
'options' => [
'min' => self::MIN,
'max' => self::MAX,
'messages' => [
StringLength::TOO_SHORT => 'Your password must be at least %min% characters',
StringLength::TOO_LONG => 'Your password must be %max% characters or fewer',
],
],
],
],
],
'password',
);
$this->add(
[
'required' => true,
'validators' => [
$this->notEmpty('Enter your password again'),
[
'name' => Identical::class,
'options' => [
'token' => self::FIELD_TO_MATCH,
'messages' => [Identical::NOT_SAME => 'The passwords do not match'],
],
],
],
],
'password_confirm',
);
}
/** @return array{name: class-string<NotEmpty>, break_chain_on_failure: true, options: array{messages: array<string, string>}} */
private function notEmpty(string $message): array
{
return [
'name' => NotEmpty::class,
'break_chain_on_failure' => true,
'options' => ['messages' => [NotEmpty::IS_EMPTY => $message]],
];
}
}
<?php
declare(strict_types=1);
namespace App\Forms\Password;
use App\Forms\Csrf\AbstractCsrfProtectedForm;
use Laminas\Form\Element\Password;
use function sprintf;
/**
* Base class for forms in which someone chooses a password
*
* Subclasses call addNewPasswordFields() from init(). Their own rules still go in
* getInputFilterSpecification(), which is added to the shared ones.
*
* @api
*
* @template TData
*
* @extends AbstractCsrfProtectedForm<TData>
*/
abstract class AbstractNewPasswordForm extends AbstractCsrfProtectedForm
{
protected function addNewPasswordFields(string $label, string $confirmLabel): void
{
$hint = sprintf('At least %d characters. A few unrelated words work well.', NewPasswordInputFilter::MIN);
$inputFilters = $this->getFormFactory()->getInputFilterFactory()->getInputFilterManager();
$this->setInputFilter($inputFilters->get(NewPasswordInputFilter::class));
$this->add([
'name' => 'password',
'type' => Password::class,
'options' => ['label' => $label, 'hint' => $hint],
'attributes' => [
'id' => 'password',
'required' => true,
'minlength' => NewPasswordInputFilter::MIN,
'autocomplete' => 'new-password',
],
]);
$this->add([
'name' => 'password_confirm',
'type' => Password::class,
'options' => ['label' => $confirmLabel],
'attributes' => ['id' => 'password_confirm', 'required' => true, 'autocomplete' => 'new-password'],
]);
}
}
The form asks one question of your data, through a one-method interface:
<?php
declare(strict_types=1);
namespace App\Forms\Register;
/** @api */
interface EmailAvailabilityInterface
{
public function isAvailable(string $email): bool;
}
A small validator turns the answer into an error message:
<?php
declare(strict_types=1);
namespace App\Forms\Register;
use Laminas\Validator\AbstractValidator;
use Laminas\Validator\ValidatorInterface;
use Override;
use function is_string;
/**
* Rejects an address that already has an account
*
* Only well formed addresses are looked up. Anything else is left for the format validator to report.
*
* @api
*/
final class EmailAvailableValidator extends AbstractValidator
{
public const string TAKEN = 'emailTaken';
public const string MESSAGE = 'An account already uses this email address. Sign in instead';
/**
* @mago-expect analysis:missing-property-type The parent declares this property without a type
*
* @var array<string, string>
*/
protected $messageTemplates = [
self::TAKEN => self::MESSAGE,
];
public function __construct(
private readonly EmailAvailabilityInterface $emails,
private readonly ValidatorInterface $format,
) {
parent::__construct();
}
#[Override]
public function isValid(mixed $value): bool
{
if (! is_string($value) || ! $this->format->isValid($value) || $this->emails->isAvailable($value)) {
return true;
}
$this->error(self::TAKEN);
return false;
}
}
The form receives the interface in its constructor, so it needs a factory:
<?php
declare(strict_types=1);
namespace App\Forms\Register;
use Psr\Container\ContainerInterface;
/** @api */
final class RegisterFormFactory
{
public function __invoke(ContainerInterface $container): RegisterForm
{
return new RegisterForm($container->get(EmailAvailabilityInterface::class));
}
}
This stand-in treats sam@example.com and pat@example.com as taken. Replace it with a query against your user storage:
<?php
declare(strict_types=1);
namespace App\Forms\Register;
use Override;
use function in_array;
use function strtolower;
/**
* Treats two addresses as taken, so that the examples can be tried. Replace it with your user storage
*
* @api
*/
final class DemoEmailAvailability implements EmailAvailabilityInterface
{
private const array TAKEN = ['pat@example.com', 'sam@example.com'];
#[Override]
public function isAvailable(string $email): bool
{
return ! in_array(strtolower($email), self::TAKEN, strict: true);
}
}
Mezzio
<?php
declare(strict_types=1);
namespace App\Handler;
use Laminas\Form\FormElementManager;
use Mezzio\Template\TemplateRendererInterface;
use Psr\Container\ContainerInterface;
/** @api */
final class RegisterHandlerFactory
{
public function __invoke(ContainerInterface $container): RegisterHandler
{
return new RegisterHandler(
$container->get(FormElementManager::class),
$container->get(TemplateRendererInterface::class),
);
}
}
<?php
declare(strict_types=1);
namespace App;
use App\Forms\Register\DemoEmailAvailability;
use App\Forms\Register\EmailAvailabilityInterface;
use App\Forms\Register\RegisterForm;
use App\Forms\Register\RegisterFormFactory;
use App\Handler\RegisterHandler;
use App\Handler\RegisterHandlerFactory;
use Laminas\ServiceManager\Factory\InvokableFactory;
/** @api */
final class RegisterConfigProvider
{
/** @return array<string, mixed> */
public function __invoke(): array
{
return [
'dependencies' => [
'aliases' => [
EmailAvailabilityInterface::class => DemoEmailAvailability::class,
],
'factories' => [
DemoEmailAvailability::class => InvokableFactory::class,
RegisterHandler::class => RegisterHandlerFactory::class,
],
],
// The form has a dependency, so the form element manager needs a factory for it
'form_elements' => [
'factories' => [
RegisterForm::class => RegisterFormFactory::class,
],
],
];
}
}
Add the provider to config/config.php, and register the route:
<?php
declare(strict_types=1);
use App\Handler\RegisterHandler;
use Mezzio\Application;
return static function (Application $app): void {
$app->route('/register', RegisterHandler::class, ['GET', 'POST'], 'register');
};
laminas-mvc
<?php
declare(strict_types=1);
namespace Application\Controller;
use App\Forms\Csrf\CsrfGuardInterface;
use Laminas\Form\FormElementManager;
use Psr\Container\ContainerInterface;
/** @api */
final class RegisterControllerFactory
{
public function __invoke(ContainerInterface $container): RegisterController
{
return new RegisterController(
$container->get(FormElementManager::class),
$container->get(CsrfGuardInterface::class),
);
}
}
Merge this file into your module configuration, as Module does in chapter 0:
<?php
declare(strict_types=1);
namespace Application;
use App\Forms\Register\DemoEmailAvailability;
use App\Forms\Register\EmailAvailabilityInterface;
use App\Forms\Register\RegisterForm;
use App\Forms\Register\RegisterFormFactory;
use Laminas\Router\Http\Literal;
use Laminas\ServiceManager\Factory\InvokableFactory;
return [
'router' => [
'routes' => [
'register' => [
'type' => Literal::class,
'options' => [
'route' => '/register',
'defaults' => ['controller' => Controller\RegisterController::class, 'action' => 'form'],
],
],
],
],
'controllers' => [
'factories' => [
Controller\RegisterController::class => Controller\RegisterControllerFactory::class,
],
],
'service_manager' => [
'aliases' => [
EmailAvailabilityInterface::class => DemoEmailAvailability::class,
],
'factories' => [
DemoEmailAvailability::class => InvokableFactory::class,
],
],
// The form has a dependency, so the form element manager needs a factory for it
'form_elements' => [
'factories' => [
RegisterForm::class => RegisterFormFactory::class,
],
],
'view_manager' => [
'template_map' => [
'forms::register' => __DIR__ . '/../../../vendor/laminas-howto/forms-shared/templates/register.phtml',
],
],
];
<?php
declare(strict_types=1);
/**
* @var Laminas\View\Renderer\PhpRenderer $this
* @var App\Forms\Register\RegisterForm $form
* @var string|null $status
*/
$form->prepare();
$this->headTitle($form->getMessages() === [] ? 'Create an account' : 'Error: Create an account', 'SET');
?>
<?= $this->partial('forms::error-summary', ['form' => $form]) ?>
<h1>Create an account</h1>
<?php if ($status !== null): ?>
<p role="status" tabindex="-1" autofocus><?= $this->escapeHtml($status) ?></p>
<?php endif; ?>
<p>All fields are required. <a href="/login">Sign in</a> if you already have an account.</p>
<?= $this->form()->openTag($form) ?>
<?= $this->formElement($form->get('csrf')) ?>
<?= $this->partial('forms::field', ['element' => $form->get('name')]) ?>
<?= $this->partial('forms::field', ['element' => $form->get('email')]) ?>
<?= $this->partial('forms::field', ['element' => $form->get('password')]) ?>
<?= $this->partial('forms::field', ['element' => $form->get('password_confirm')]) ?>
<?= $this->partial('forms::checkbox', ['element' => $form->get('terms')]) ?>
<?= $this->formElement($form->get('register')) ?>
<?= $this->form()->closeTag() ?>
It uses the checkbox partial from chapter 2. Register it under forms::checkbox if you skipped that chapter:
<?php
declare(strict_types=1);
/**
* @var Laminas\View\Renderer\PhpRenderer $this
* @var Laminas\Form\Element\Checkbox $element
*/
$id = (string) $element->getAttribute('id');
if ($element->getMessages() !== []) {
$element->setAttribute('aria-invalid', 'true');
$element->setAttribute('aria-describedby', $id . '-error');
}
?>
<div class="field checkbox">
<?= $this->formElementErrors($element, ['class' => 'error', 'id' => $id . '-error']) ?>
<?= $this->formElement($element) ?>
<?= $this->formLabel($element) ?>
</div>
<?php
declare(strict_types=1);
namespace App\Handler;
use App\Csrf\MezzioCsrfGuard;
use App\Forms\Register\RegisterForm;
use Laminas\Diactoros\Response\HtmlResponse;
use Laminas\Diactoros\Response\RedirectResponse;
use Laminas\Form\FormElementManager;
use Mezzio\Csrf\CsrfGuardInterface;
use Mezzio\Csrf\CsrfMiddleware;
use Mezzio\Flash\FlashMessageMiddleware;
use Mezzio\Flash\FlashMessagesInterface;
use Mezzio\Template\TemplateRendererInterface;
use Override;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/** @api */
final readonly class RegisterHandler implements RequestHandlerInterface
{
public function __construct(
private FormElementManager $forms,
private TemplateRendererInterface $renderer,
) {}
#[Override]
public function handle(ServerRequestInterface $request): ResponseInterface
{
/** @var CsrfGuardInterface $guard */
$guard = $request->getAttribute(CsrfMiddleware::GUARD_ATTRIBUTE);
/** @var FlashMessagesInterface $flash */
$flash = $request->getAttribute(FlashMessageMiddleware::FLASH_ATTRIBUTE);
$form = $this->forms->get(RegisterForm::class);
$form->setCsrfGuard(new MezzioCsrfGuard($guard));
if ($request->getMethod() === 'POST') {
/** @var array<string, mixed> $data */
$data = $request->getParsedBody();
$form->setData($data);
if ($form->isValid()) {
// Create the account here from $form->getData(). Store only password_hash($password, PASSWORD_ARGON2ID)
$flash->flash('status', 'Your account has been created.');
return new RedirectResponse('/register', 303);
}
}
return new HtmlResponse($this->renderer->render('forms::register', [
'form' => $form,
'status' => $flash->getFlash('status'),
]));
}
}
<?php
declare(strict_types=1);
namespace Application\Controller;
use App\Forms\Csrf\CsrfGuardInterface;
use App\Forms\Register\RegisterForm;
use Laminas\Form\FormElementManager;
use Laminas\Http\Request;
use Laminas\Http\Response;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Mvc\Plugin\FlashMessenger\FlashMessenger;
use Laminas\Stdlib\Parameters;
use Laminas\View\Model\ViewModel;
/** @api */
final class RegisterController extends AbstractActionController
{
public function __construct(
private readonly FormElementManager $forms,
private readonly CsrfGuardInterface $guard,
) {}
public function formAction(): Response|ViewModel
{
$form = $this->forms->get(RegisterForm::class);
$form->setCsrfGuard($this->guard);
/** @var Request $request */
$request = $this->getRequest();
/** @var FlashMessenger $flash */
$flash = $this->plugin('flashMessenger');
if ($request->isPost()) {
/** @var Parameters $post */
$post = $request->getPost();
$form->setData($post->toArray());
if ($form->isValid()) {
// Create the account here from $form->getData(). Store only password_hash($password, PASSWORD_ARGON2ID)
$flash->addSuccessMessage('Your account has been created.');
return $this->redirect()->toRoute('register')->setStatusCode(303);
}
}
$view = new ViewModel([
'form' => $form,
'status' => $flash->getSuccessMessages()[0] ?? null,
]);
return $view->setTemplate('forms::register');
}
}
How it works
Forms with dependencies go in form_elements. Register a factory there and the FormElementManager builds the form, then calls init() as usual.
Adding to an element's own rules. The Email element already trims and checks the format. The input filter adds to those rules instead of replacing them. This field needs two different messages, so it cannot use error_message, which would hide "already uses this email address":
- the format message is set on the element's own validator
NotEmptyhas a higherpriority, so a blank field reports once- the availability validator skips anything the format validator rejects, so your storage is only asked about real addresses
Rules in two places, one input filter. setInputFilter() supplies the password rules, and the form's own getInputFilterSpecification() is added to them. Fetching the filter from the input filter plugin manager calls its init() and gives each form a fresh copy. Identical can still see password, because both fields are in the same filter.
Why not the Callback validator? It catches exceptions and reports them as invalid input, so a database outage would look like a bad email address.
The database has the last word. Two people can register the same address at the same moment. Put a unique index on the column and handle the failure when saving.
This reveals who has an account. Chapter 2 avoids that. Saying "already taken" is friendly and common, but if membership of your site is sensitive, respond the same way for every address and explain by email instead.
Length, not complexity. The rules follow NIST SP 800-63B: at least 15 characters when a password is the only factor, no demands for symbols or digits, and room for at least 64. Length is counted in characters, not bytes. Nothing is trimmed or cut off.
Two password fields. WCAG 2.2 "Redundant Entry" generally forbids asking for the same thing twice, but allows it when creating a password that is not displayed. autocomplete="new-password" lets a password manager fill both.
An unticked box still sends a value. The Checkbox element accepts '0', and required does not mean ticked. The InArray rule accepts only '1'.
Before you use this for real
- Hash the password with
password_hash($password, PASSWORD_ARGON2ID). The default, bcrypt, ignores everything after 72 bytes. Check that your PHP build offers Argon2id. - Reject common and breached passwords. NIST requires it, and this example does not do it.
- Confirm the email address before trusting the account.
- Limit how often one visitor can register, which also slows down guessing which addresses are taken.
- Link to your terms next to the checkbox, outside its label, and record which version was accepted.
Further opportunities
None of these are built or tested here. Add the ones your site needs.
| Opportunity | Where | How |
|---|---|---|
| Check passwords against a blocklist | Input filter | Add a validator to password, using a local list or a breach-checking service |
| Hide which addresses are taken | Handler or controller | Always answer "Check your email", then send either a confirmation or a "you already have an account" message |
| Show the password | Template and a little JavaScript | A "Show password" button can replace the second field |
| Stop automated sign-ups | Form or middleware | A hidden "honeypot" field, a challenge service, or limits per IP address |
| Block disposable addresses | Input filter | Add a validator that checks the domain against a list |
| Offer passkeys | A separate WebAuthn flow | Let people register without a password |
| Sign in straight away | Where the "Create the account here" comment is | Regenerate the session ID first, as in chapter 2 |
| Ask for more later | A profile page | Keep registration short, and collect the rest after sign-up |
Common mistakes
- Forgetting the
form_elementsfactory. The manager then callsnew RegisterForm()with the form name, and you get aTypeErrorsaying a string was given whereEmailAvailabilityInterfacewas expected. - Registering that factory under
dependenciesorservice_manager. TheFormElementManagerdoes not look there. - Using
error_messageon a field that can fail for more than one reason. - Creating the input filter with
new NewPasswordInputFilter().init()is not called, so it has no rules. - Adding
maxlengthto a password field. - Relying on the
requiredattribute for the terms checkbox.