Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Document RequestValidator #17786

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
add first lines of docs
  • Loading branch information
Thomas Hanke committed Jan 21, 2023
commit 0f7fb95eb6e0fedb23a32cc622b652effb6d69df
59 changes: 59 additions & 0 deletions 59 validation/request_inputs.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
.. index::
single: Validation; Validating request inputs

How to Validate Request Inputs
==============================

Most of the time, you first validate a request to see if the data
sent is valid. To end the call early with a "BadRequestResponse"
in case of incorrect data.

With the attribute RequestValidator in front of your action method
you can fill a previously defined request class with the sent data
and validate it automatically. If the data is incorrect, an exception
is thrown before the request arrives in the controller method.

RequestClass
------------

A very simple example of a GetUserRequest would look like this:

// src/Request/GetUserRequest.php
namespace App\Request;

use Symfony\Component\Validator\Constraints as Assert;

class GetUserRequest
{
#[Assert\Type(type: 'digit')]
#[Assert\NotBlank]
public $id;

public function getId(): int
{
return intval($this->id);
}
}

ControllerClass
---------------

And the controller would look like this in the above example:

// src/Controller/GetUserAction.php
namespace App\Controller;

use App\Request\GetUserRequest;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Attribute\RequestValidator;

class GetUserAction
{
#[Route(path: '/user', methods: ['GET']]
#RequestValidator[class: GetUserRequest::class]
public __invoke(GetUserRequest $request)
{
$userId = $request->getId();
...
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.