Skip to content

Commit

Permalink
Add validator to Text type sign-up list field
Browse files Browse the repository at this point in the history
Adds `NotEmpty` validator and a `StringTrim` filter to make sure the
field value is never the empty string.
  • Loading branch information
tomudding committed Sep 9, 2023
1 parent 777948a commit 59ec6a2
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
55 changes: 55 additions & 0 deletions module/Activity/src/Form/Element/ValidatedText.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

declare(strict_types=1);

namespace Activity\Form\Element;

use Laminas\Filter\StringTrim;
use Laminas\Form\Element\Text;
use Laminas\InputFilter\InputProviderInterface;
use Laminas\Validator\NotEmpty;
use Laminas\Validator\ValidatorInterface;

class ValidatedText extends Text implements InputProviderInterface
{
protected ?ValidatorInterface $validator = null;

/**
* Get primary validator.
*/
protected function getValidator(): ValidatorInterface
{
if (null === $this->validator) {
$this->validator = new NotEmpty(NotEmpty::STRING);
}

return $this->validator;
}

/**
* Provide default input rules for this element
*
* Attaches a not empty validator and a string trim filter.
*
* @inheritDoc
*/
public function getInputSpecification(): array
{
$spec = [
'required' => true,
'filters' => [
['name' => StringTrim::class],
],
'validators' => [
$this->getValidator(),
],
];

$name = $this->getName();
if (null !== $name) {
$spec['name'] = $name;
}

return $spec;
}
}
3 changes: 2 additions & 1 deletion module/Activity/src/Form/Signup.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Activity\Form;

use Activity\Form\Element\ValidatedText;
use Activity\Model\SignupField as SignupFieldModel;
use Activity\Model\SignupList as SignupListModel;
use Laminas\Captcha\Image as ImageCaptcha;
Expand Down Expand Up @@ -135,7 +136,7 @@ protected function createSignupFieldElementArray(SignupFieldModel $field): array

switch ($field->getType()) {
case 0: //'Text'
$result['type'] = 'Text';
$result['type'] = ValidatedText::class;
break;
case 1: //'Yes/No'
$result['type'] = Radio::class;
Expand Down

0 comments on commit 59ec6a2

Please sign in to comment.