Answer the question
In order to leave comments, you need to log in
How to properly apply Symfony Validator?
Hello everyone, I downloaded the Symfony Validato component, I'm trying to attach it to myself. I have a class that works with the CRM API, fields are filled in on the first page, I do this
$shippingFirstName = $_REQUEST['shippingFirstName'];
$shippingLastName = $_REQUEST['shippingLastName'];
$validator = Validation::createValidator();
$constraint = new Assert\Collection(array(
'shippingFirstName' => array(
new Assert\Length(array('min' => 10)),
new Assert\NotBlank(['message' => 'The value of the "First Name" field should not be blank']),
new Assert\Email(['message' => 'The email {{ value }} is not a valid email.']),
),
'shippingLastName' => array(
new Assert\Length(array('min' => 10)),
new Assert\NotBlank(['message' => 'The value of the "Last Name" field should not be blank']),
new Assert\Email(['message' => 'The email {{ value }} is not a valid email.']),
)
));
$violations = $validator->validate(['shippingFirstName' => $shippingFirstName, 'shippingLastName' => $shippingLastName], $constraint);
if (count($violations) !== 0 ) {
foreach ($violations as $violation) {
echo $violation->getMessage().'<br>';
}
exit;
}
Answer the question
In order to leave comments, you need to log in
I would put the logic of building a constraint in a separate class, something like ShippingConstraint, for reuse (and not to clutter up the controller with validation details). See symfony.com/doc/current/validation/custom_constrai...
Then your code will look something like this:
$validator = Validation::createValidator();
$violations = $validator->validate([
'shippingFirstName' =>$_REQUEST['shippingFirstName'],
'shippingLastName' => $_REQUEST['shippingFirstName'],
], new ShippingConstraint());
if (count($violations) !== 0 ) {
foreach ($violations as $violation) {
echo $violation->getMessage().'<br>';
}
exit;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question