Zend Input Filters & Validators

Input Filters clean and normalize raw input (e.g., trim whitespace, strip tags).

Validators enforce rules (e.g., required, length, format, uniqueness).


Common Filters

Filter

Description

Valid Input Example

Filtered Output

Code Snippet

StringTrim

Trims whitespace from beginning/end

' Hello World '

'Hello World'

['name' => 'StringTrim']

StripTags

Removes HTML tags

'<p>Hello <b>World</b></p>'

'Hello World'

['name' => 'StripTags']

ToInt

Casts value to integer

'123.45'

123

['name' => 'ToInt']

ToFloat

Converts to float (decimal)

'123.45'

123.45

['name' => 'ToFloat']

StringToLower

Converts all characters to lowercase

'Hello World'

'hello world'

['name' => 'StringToLower']

Null

Converts empty string to null

''

null

['name' => 'Null']

Boolean

Converts values to true or false

'yes','0','true'

true,false,true

['name' => 'Boolean']

NormalizeToAscii

Remove accents & normalize Unicode

'Crème Brûlée'

'Creme Brulee'

['name' => 'NormalizeToAscii']

PregReplace

Replace patterns with regex

'abc123'

'abc'(e.g. remove digits)

['name' => 'PregReplace', 'options' => ['pattern' => '/\d/', 'replacement' => '']]

Common Validators

Validator

Purpose

Code Snippet with messages

Valid Input Example

NotEmpty

Value must not be empty

'validators' => [
    [ 'name' => 'NotEmpty', 
      'options' => [ 
        'messages' => [ 
          \Laminas\Validator\NotEmpty::IS_EMPTY => 'This field is required.'
        ], 
      ], 
    ]
  ]


'John'

StringLength

Enforce min/max length

'validators' => [
  [ 
    'name' => 'StringLength', 
    'options' => [ 
      'min' => 8, 
      'max' => 20, 
      'messages' => [ 
        \Laminas\Validator\StringLength::TOO_SHORT => 'Password must be at least 8 characters', \Laminas\Validator\StringLength::TOO_LONG => 'Password must not exceed 20 characters', 
      ], 
    ], 
  ]
]


'MySecurePwd'

EmailAddress

Valid email format

'validators' => [
  [ 
    'name' => 'EmailAddress', 
    'options' => [ 
      'messages' => [ 
        \Laminas\Validator\EmailAddress::INVALID_FORMAT => 'Please enter a valid email address', 
      ], 
    ], 
  ]
]


'user@example.com'

Regex

Match a specific pattern

'validators' => [
  [ 
    'name' => 'Regex', 
    'options' => [ 
      'pattern' => '/^[a-zA-Z0-9]+$/', 
      'messages' => [ 
        \Laminas\Validator\Regex::NOT_MATCH => 'Only alphanumeric characters allowed', 
      ], 
    ], 
  ]
]


'Alpha123'

Callback

Custom logic using PHP callable

'validators' => [
  [ 
    'name' => 'Callback', 
    'options' => [ 
      'callback' => fn($val) => $val === 'yes', 
      'messages' => [ 
        \Laminas\Validator\Callback::INVALID_VALUE => 'Only "yes" is accepted', 
      ], 
    ], 
  ]
]


'yes'

InArray

Must be one of specified values

'validators' => [
  [ 
    'name' => 'InArray', 
    'options' => [ 
      'haystack' => [
        'admin', 'user'
      ], 
      'messages' => [ 
       \Laminas\Validator\InArray::NOT_IN_ARRAY => 'Select a valid role', 
      ], 
    ], 
  ]
]


'admin'

Digits

Allow only digits

'validators' => [
  [ 
    'name' => 'Digits', 
    'options' => [ 
      'messages' => [ 
        \Laminas\Validator\Digits::NOT_DIGITS => 'Only numbers are allowed', 
      ], 
    ], 
  ]
]


'123456'

Between

Numeric range enforcement

'validators' => [
  [ 
    'name' => 'Between', 
    'options' => [ 
      'min' => 18, 
      'max' => 60, 
      'messages' => [ 
        \Laminas\Validator\Between::NOT_BETWEEN => 'Value must be between 18 and 60', 
      ], 
    ], 
  ]
]


'25'

Identical

Compare with another field

'validators' => [
  [ 
    'name' => 'Identical', 
    'options' => [ 
      'token' => 'password', 
      'messages' => [ 
        \Laminas\Validator\Identical::NOT_SAME => 'Passwords do not match', 
      ], 
    ], 
  ]
]


'secret123'(same as password)


Example: InputFilter Attached to a Form

1. Form class implementing InputFilterProviderInterface (module/Application/src/Form/RegisterForm.php)

namespace Application\Form;

use Laminas\Form\Form;
use Laminas\InputFilter\InputFilterProviderInterface;

class RegisterForm extends Form implements InputFilterProviderInterface
{
  public function __construct()
  {
    parent::__construct('register');

    $this->add([
      'name' => 'email',
      'type' => 'Email',
      'options' => ['label' => 'Email Address'],
    ]);

    $this->add([
      'name' => 'password',
      'type' => 'Password',
      'options' => ['label' => 'Password'],
    ]);

    $this->add([
      'name' => 'confirm_password',
      'type' => 'Password',
      'options' => ['label' => 'Confirm Password'],
    ]);

    $this->add([
      'name' => 'submit',
      'type' => 'Submit',
      'attributes' => ['value' => 'Register'],
    ]);
  }

  public function getInputFilterSpecification(): array
  {
    return [
      'email' => [
        'required' => true,
        'filters' => [
          ['name' => 'StringTrim'],
          ['name' => 'StripTags'],
          ['name' => 'StringToLower'],
        ],
        'validators' => [
          [
            'name' => 'EmailAddress',
            'options' => [
              'allow' => \Laminas\Validator\Hostname::ALLOW_DNS,
              'useMxCheck' => false,
            ],
          ],
        ],
      ],
      'password' => [
        'required' => true,
        'filters' => [
          ['name' => 'StringTrim'],
        ],
        'validators' => [
          [
            'name' => 'StringLength',
            'options' => [
              'min' => 8,
              'max' => 64,
              'messages' => [
                \Laminas\Validator\StringLength::TOO_SHORT => 'Password must be at least 8 characters',
              ],
            ],
          ],
        ],
      ],
      'confirm_password' => [
        'required' => true,
        'filters' => [
          ['name' => 'StringTrim'],
        ],
        'validators' => [
          [
            'name' => 'Identical',
            'options' => [
              'token' => 'password',
              'messages' => [
                \Laminas\Validator\Identical::NOT_SAME => 'Passwords do not match',
              ],
            ],
          ],
        ],
      ],
    ];
  }
}


2. Controller Usage

public function registerAction()
{
  $form = new \Application\Form\RegisterForm();
  $request = $this->getRequest();

  if ($request->isPost()) {
    $form->setData($request->getPost());

    if ($form->isValid()) {
      $data = $form->getData();
      // Proceed (e.g., create user)
    } else {
      // $form->getMessages() contains validation errors
    }
  }

  return new ViewModel(['form' => $form]);
}


3. View Rendering

<?= $this->form()->openTag($form) ?>
<?= $this->formRow($form->get('email')) ?>
<?= $this->formRow($form->get('password')) ?>
<?= $this->formRow($form->get('confirm_password')) ?>
<?= $this->formSubmit($form->get('submit')) ?>
<?= $this->form()->closeTag() ?>

Errors will be shown per field automatically when using formRow.


Custom Validator Example (module\Application\src\Form\NoAdminNameValidator.php)

use Laminas\Validator\AbstractValidator;

class NoAdminNameValidator extends AbstractValidator
{
  const INVALID = 'invalidName';

  protected $messageTemplates = [
    self::INVALID => "The name 'admin' is not allowed.",
  ];

  public function isValid($value)
  {
    $this->setValue($value);
    if (strtolower($value) === 'admin') {
      $this->error(self::INVALID);
      return false;
    }
    return true;
  }
}


Then in input filter:

use Application\Form\NoAdminNameValidator;

'username' => [
  'required' => true,
  'validators' => [
    [
      'name' => NoAdminNameValidator::class,
    ],
  ],
],


if input value is admin means it show "The name 'admin' is not allowed."


Best Practices

  • Always filter raw input before validation.
  • Use specific validators instead of loose Callback where possible.
  • Leverage error messages for user feedback.
  • Group related filters/validators via fieldsets for reuse.
  • Use CSRF element to protect forms.

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.