Symfony 1.4 conditional validation

Asked
Active3 hr before
Viewed126 times

8 Answers

validationsymfonyconditional
90%

The password can only be validated if you also have access to the username value. But as you might know, a validator attached to a field does not have access to the other values of the form., symfony1 Legacy ,That's quite easy to accomplish by throwing an error bound to the password field instead of throwing a global error:, Projects using Symfony

Here is the first implementation of the login form:

class loginForm extends sfForm {
   public
   function configure() {
      $this - > setWidgets(array(
         'username' => new sfWidgetFormInput(),
         'password' => new sfWidgetFormInputPassword(),
      ));

      $this - > setValidators(array(
         'username' => new sfValidatorString(array('required' => true)),
         'password' => new sfValidatorString(array('required' => true)),
      ));

      $this - > widgetSchema - > setNameFormat('login[%s]');
   }
}
load more v
88%

current_password: you should create a callback type post validator for this,I have a Profile form that inherits from sfGuardRegisterForm , Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers ,Making statements based on opinion; back them up with references or personal experience.

current_password: you should create a callback type post validator for this

// in sfGuardRegisterForm::configure()

// these fields can be blank
$this - > getValidator('current_password') - > setOption('required', false);
$this - > getValidator('new_password') - > setOption('required', false);
$this - > getValidator('password_again') - > setOption('required', false);

// check the current password (this validator is not `required` by default)
$this - > mergePostValidator(new sfValidatorCallback(array(
   'callback' => array($this, 'checkPassword'),
), array(
   'invalid' => 'Incorrect current password.'
)));

// add this method to the same form class
public
function checkPassword(sfValidatorBase $validator, array $values, array $arguments) {
   // if a new password is given check whether the old one is correct or not and rise an error if not correct
   if (0 != strlen($values['new_password']) && !$this - > getObject() - > checkPassword($values['current_password'])) {
      throw new sfValidatorErrorSchema($validator, array(
         'current_password' => new sfValidatorError($validator, 'invalid')
      ));
   }

   return $values;
}
load more v
72%

20. Validation Groups: Conditional Validation 2:00 ,Here's how you do it: take advantage of something called validation groups. On the NotBlank constraint, add groups={"Registration"}:, 19. Validation with the UniqueEntity Constraint 2:40 ,That should do it. Refresh: validation is back.

What PHP libraries does this tutorial use?

// composer.json
{
   "require": {
      "php": ">=5.5.9",
      "symfony/symfony": "3.1.*", // v3.1.4
      "doctrine/orm": "^2.5", // v2.7.2
      "doctrine/doctrine-bundle": "^1.6", // 1.6.4
      "doctrine/doctrine-cache-bundle": "^1.2", // 1.3.0
      "symfony/swiftmailer-bundle": "^2.3", // v2.3.11
      "symfony/monolog-bundle": "^2.8", // 2.11.1
      "symfony/polyfill-apcu": "^1.0", // v1.2.0
      "sensio/distribution-bundle": "^5.0", // v5.0.22
      "sensio/framework-extra-bundle": "^3.0.2", // v3.0.16
      "incenteev/composer-parameter-handler": "^2.0", // v2.1.2
      "composer/package-versions-deprecated": "^1.11", // 1.11.99
      "knplabs/knp-markdown-bundle": "^1.4", // 1.4.2
      "doctrine/doctrine-migrations-bundle": "^1.1" // 1.1.1
   },
   "require-dev": {
      "sensio/generator-bundle": "^3.0", // v3.0.7
      "symfony/phpunit-bridge": "^3.0", // v3.1.3
      "nelmio/alice": "^2.1", // 2.1.4
      "doctrine/doctrine-fixtures-bundle": "^2.3" // 2.3.0
   }
}
65%

Symfony validator for conditional validations based on object properties ,Symfony validator for conditional validations based on object properties, Symfony validator for conditional validations based on object properties , Why GitHub? Features → Mobile → Actions → Codespaces → Packages → Security → Code review → Issues → Integrations → GitHub Sponsors → Customer stories →

$ composer require bcastellano / symfony - validator - conditional
load more v
75%

Can I pass all these values to a constraint somehow, and compare them there?,For case 3 you can use AssertGreaterThanOrEqual constraint directly on Count2 field.,but I expect it's better practice to fully reconstruct the form again as per your first line.,Generally, what is the best practice in this case?

For example, in your entity class:

< ? php

use SymfonyComponentValidatorConstraints as Assert;

/**
 * @AssertCallback(methods={"myValidation"})
 */
class Setting {
   public
   function myValidation(ExecutionContextInterface $context) {
      if (
         $this - > getRadioSelection() == '1' // RADIO SELECT EXAMPLE
         &&
         ( // CHECK OTHER PARAMS
            $this - > getFiled1() == null
         )
      ) {
         $context - > addViolation('mandatory params');
      }
      // put some other validation rule here
   }
}
load more v
40%

Add a custom conditional validation on a Symfony form , Ajax submission of a Symfony form with Vue-resource and a FormData object   ,Sometimes validating each field of a form is not enough. In some cases you need a conditional validation. That means that the validation of a field or a set of fields will be conditioned by another field's value. Here is a simple example showing how to validate an end date, but only if a value was set. It will also show you how to manually submit values to a form without using the current request.


<?php

declare(strict_types=1);

// src/Form/EventCreateType.php

namespace App\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

/**
 * We set a global validation on the form. Not on a specific field.
 */
final class EventCreateType extends AbstractType
{
    /**
     * We remove csrf as we manually submit values to the form.
     */
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'csrf_protection' => false,
            'constraints' => [
                new Callback([$this, 'validate']),
            ],
        ]);
    }

    /**
     * Valid if the end date if not set or if it is greater than the start date.
     * If the second test, we are sure both fields are DateTime objects.
     *
     * @param array<string,mixed> $data
     */
    public function validate(array $data, ExecutionContextInterface $context): void
    {
        if (($data['end_date'] instanceof \DateTime) && $data['start_date'] > $data['end_date']) {
            $context->buildViolation('The end date must be greater than the start date.')
                ->atPath('end_date')
                ->addViolation();
        }
    }

    /**
     * Only the start date is mandatory.
     *
     * @param array<string,mixed> $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->add('start_date', DateType::class, [
            'widget' => 'single_text',
            'constraints' => [new NotBlank()],
        ]);

        $builder->add('end_date', DateType::class, [
            'widget' => 'single_text',
        ]);
    }
}
load more v
22%

Conditional validation of fields based on other field value in Symfony2 So here is the scenario: I have a radio button group. Based on their value, I should or shouldn't validate other three fields (are they blank, do they contain n... ramon.lueilwitz · saved on 5 months ago ,So here is the scenario: I have a radio button group. Based on their value, I should or shouldn't validate other three fields (are they blank, do they contain n...,I am working on a registration form where I need to put a validation on email id, if the email domain does not belong to a specific domain then person should no...,So here is the scenario: I have a radio button group. Based on their value, I should or shouldn't validate other three fields (are they blank, do they contain numbers, etc).

For example, in your entity class:

< ? php

use SymfonyComponentValidatorConstraints as Assert;

/**
 * @AssertCallback(methods={"myValidation"})
 */
class Setting {
   public
   function myValidation(ExecutionContextInterface $context) {
      if (
         $this - > getRadioSelection() == '1' // RADIO SELECT EXAMPLE
         &&
         ( // CHECK OTHER PARAMS
            $this - > getFiled1() == null
         )
      ) {
         $context - > addViolation('mandatory params');
      }
      // put some other validation rule here
   }
}
60%

github.com/bcastellano/symfony-validator-conditional ,Symfony validator for conditional validations based on object properties, symfonyphpSymfony2validatorconditionsymfony3,symfony/validator: ~2.0

The recommended way to install is through composer:

$ composer require bcastellano / symfony - validator - conditional
load more v

Other "validation-symfony" queries related to "Symfony 1.4 conditional validation"