user1483208
user1483208

Reputation: 385

Validate dates one after another

I have form in which user inputs 3 datetimes and I want check if second date is after first, and third date is after the second. How to do that? It should be done after

if ($form->isValid()) {

(just before database update) or somehow with validation groups(I'm new to symfony2)?

Upvotes: 0

Views: 173

Answers (2)

tomazahlin
tomazahlin

Reputation: 2167

Building your own constraints is a good practice, because the validator constraints become reusable. If you only require that kind of validation in one of your entities, you can also do this:

yml:

Project\Bundle\SomeBundle\Entity\Something:
    getters:
        datesOrderValid:
          - "True": { message: 'Dates are not in valid order.' }

in your entity:

public function isDatesOrderValid()
{
    // Compare dates (probably in datetime) here and return true if they are in valid order, otherwise return false
}

Upvotes: 1

Ahmed Siouani
Ahmed Siouani

Reputation: 13891

If your form is populated via an object that maps the three date field you want to validate, You may then consider using a Custom Validation Constraint,

First, add a Class Constraint that looks like,

namespace Namespace\BundleName\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class DateCoherence extends Constraint
{
    public $message = 'The error message you want to show when the validation fails.';

    public function getTargets()
    {
        return self::CLASS_CONSTRAINT;
    }

    public function validatedBy()
    {
        return get_class($this).'Validator'; // You can also use an alias here
    }
}

The Validator,

namespace Namespace\BundleName\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class DateCoherenceValidatorValidator extends ConstraintValidator
{
    public function validate($object, Constraint $constraint)
    {
        if ($object->getFirstDate() > $object->getSecondDate() || $object->getSecondDate() > $object->getThirdDate()) {
            $this->context->addViolation($constraint->message);
        }
    }
}

Your Constraint should then be added to your class via a,

use Namespace\BundleName\Validator\Constraints as YourAssert;

/**
 * @YourAssert\DateCoherence(groups={"dates"})
 */
class YourClass
{

Adding a validation group here allows you to only check only the validation against your constraint date everywhere you want to. (For example, within your controller)

$errors = $this->get('validator')->validate($object, array('dates'));

Upvotes: 2

Related Questions