A
A
Alexey Verkhovtsev2017-09-23 14:22:12
symfony
Alexey Verkhovtsev, 2017-09-23 14:22:12

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;
        }

How much is right, wrong? Thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
voronkovich, 2017-09-23
@voronkovich

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 question

Ask a Question

731 491 924 answers to any question