I need to validate an array. And I also have to validate the values in this array.
For example I want to validate each of these entries and only this one. If I have anything else I want an error. But I can send only one entry if I want. How can I validate that?
"workDaysInput": [
"full-week",
"partial-week-3-4",
"partial-week-1-2",
"night-and-weekend"
],
CodePudding user response:
This depends on the context and where the array is used. But you can use the validation component. For more details see https://symfony.com/doc/current/validation.html
Here is a quick easy example if you are using an entity. if you need to do this validation in alot of places I recommend creating your own validation constraint. see here for the details https://symfony.com/doc/current/validation/custom_constraint.html
For this example we will use a callback constraint see https://symfony.com/doc/current/reference/constraints/Callback.html.
Add the following to your php file. When this class gets run through the validator it will read the annotation and run the validate function. Using a validation callback You will need to check each property individually and set the error for each constraint, in this example we are checking workDaysInput
.
You will need to include the following use statements at the top of your class.
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @Assert\Callback
*/
public function validate(ExecutionContextInterface $context, $payload){
$workDays = $this->getWorkDaysInput();
$allowedDays = [
"full-week",
"partial-week-3-4",
"partial-week-1-2",
"night-and-weekend"
];
if(count($workDays) < 1 && count($workDays) > 4) {
return $context->buildViolation('Incorrect amount of options selected')
->atPath('workDays')
->addViolation();
}
forEach($workDays as $day){
if(in_array($day, $allowedDays)) return $context->buildViolation(sprintf('Day selection %s not allowed', $day))
->atPath('workDays')
->addViolation();
}
}