Why do I receive This value should be of type string when using a DateTime constraint on Symfony 5?
You are using the wrong of assertion.
Date
expects a string or an object that can be cast into a string. And a DateTimeInterface
is neither.
You should be using a Type
constraint.
/**
* @Assert\Type("\DateTimeInterface")
*/
private $createdAt;
The ability to use Assert\Date
to validate DateTime
objects was deprecated on Symfony 4.2, and on Symfony 5.0 it was removed altogether.
Symfony form: Uploaded file - This value should be of type string
In config/packages/validator.yaml
comment out these lines if they exist:
framework:
validation:
# Enables validator auto-mapping support.
# For instance, basic validation constraints will be inferred from Doctrine's metadata.
#auto_mapping:
# App\Entity\: []
See Symfony 4.3 issue [Validation] Activate auto-mapped validation via an annotation #32070.
Symfony constraint to prevent duplicates in overlapping time frame
The cleaner way would be to create your own custom assert.
Starting by creating your constraint :
<?php
namespace App\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class TaxComponentConstraint extends Constraint
{
public $message = 'Another tax component overlap this one: {{ taxComponent}}';
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
public function validatedBy()
{
return 'App\Validator\Constraints\TaxComponentValidator';
}
}
And now you have to create a validator that will check if there exist an overlap with two tax component.
<?php
namespace App\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class TaxComponentValidator extends ConstraintValidator
{
public function validate($taxComponentObject, Constraint $constraint)
{
//Check however you want if the tax component can be created (So no overlap between two existing TaxComponent)
if($overlappingTaxComponent){
$this->context->buildViolation($constraint->message)
->setParameter('{{ taxComponent }}', $overlappingTaxComponent->__toString())
->addViolation();
}
}
}
Here, $overlappingTaxComponent is a TaxComponent preventing us from making one because of your constraint.
If the constraint is properly done, you can now use it easily in your entity so that it check automatically when submitting the form :
<?php
//...
use App\Validator\Constraints as CustomAssert;
/**
* @ORM\Entity
* @ORM\Table("tax_component")
* @CustomAssert\TaxComponentConstraint
*/
class TaxComponent
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(name="tax_component_id", type="integer")
*/
private ?int $id;
/**
* @ORM\Column(name="tax_component_name", type="string", length=20)
*/
private string $name;
How to set option for validation constraint in Symfony globally?
You can create a custom constraint extending Symfony\Component\Validator\Constraints\DateTime
and set the format there.
// src/Validator/Constraints/MyDateTime.php
namespace App\Validator\Constraints;
use Symfony\Component\Validator\Constraints\DateTime as BaseDateTime;
class MyDateTime extends BaseDateTime
{
public $format = 'Y-m-d\TH:i:s.vP';
public function validatedBy()
{
// use the same validator without this symfony will look for 'App\Validator\Constraints\MyDateTimeValidator'
//return static::class.'Validator';
return parent::class.'Validator';
}
}
Then you just use custom constraint where needed.
YAML:
# config/validator/validation.yaml
App\Entity\Author:
properties:
createdAt:
- NotBlank: ~
- App\Validator\Constraints\MyDateTime: ~
Annotations:
// src/Entity/Author.php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use App\Validator\Constraints as MyAssert;
class Author
{
/**
* @Assert\NotBlank
* @MyAssert\MyDateTime
* @var string A "Y-m-d\TH:i:s.vP" formatted value
*/
protected $createdAt;
}
So your config would look like this:
dateFrom:
- App\Validator\Constraints\MyDateTime: ~
https://symfony.com/doc/current/validation/custom_constraint.html
Symfony Validation Constraint Assert\Date() is accepting empty string
This is the expected behaviour.
You are not missing anything, there is no option in the definition of the Date constraint to invalidate for empty value in the field.
To invalidate for empty value in the field, you should add the NotBlank Constraint, as you correctly state.
Here is the line: code for DateValidator
For example this is the same for most other validators, eg. LengthValidator will validate for empty string, even if min is >0.
References:
- Similar answer
- Github issue
- Explanation
Symfony constraint LessThan Date
In your case, 2 strings are compared by the LessThan validator
You should convert the request value of birthdate
to an object of DateTime
before validation.
Related Topics
How to Access the Google Spreadsheets API in PHP
Converting Human-Friendly Date to Milliseconds
Symfony & Guard: "The Security Token Was Removed Due to an Accountstatusexception"
How to Replace Some Characters with Asterisks
How to Launch a PHP Script at Apache Startup
How to Curry Method Calls in PHP
PHP HTML Decoding Help - Converting: a 'Quote' Is <B>Bold</B>
Date Function to Display All Dates Between Two Dates
Is Auto-Initialization of Multi-Dimensional Hash Array Possible in Ruby, as It Is in PHP
How to Take a Screenshot of a Website with PHP and Gd
Laravel Get Route Name from Given Url
Phpunit: Doing Assertions on Non-Public Variables
Setting $_Session Doesn't Work on Localhost Using Xampp
How to Detect If a User Uploaded a File Larger Than Post_Max_Size
Difference(When Being Applied to My Code) Between Int(10) and Int(12)
Pdo SQL-State "00000" But Still Error
Wordpress, Nginx Proxy and Subdirectory: Wp-Login.PHP Redirects to Domain