Kristian Lunde

www.klunde.net

Archive for the ‘Zend’ tag

Zend_Input_Filter and the Alnum Validator

without comments

The Zend_Input_Filter is a very useful tool when you need to validate and filter the input to your application. It allows you to both filter and validate the input without a lot of hassle. One of the cool features it has is that it allows you to add the validators you need and meta commands to each validator. For instance you can set an Alnum validator to allow empty fields, set a default text and so on.

I came over this annoying issue the other day when I tried to setup the Alnum validator to allow white spaces and have a few meta commands attached to the validator chain. The manual says that you can do this:

  1. $validators = array(
  2.     'month'   => array(
  3.         'Digits',                // string
  4.         new Zend_Validate_Int(), // object instance
  5.         array('Between', 1, 12)  // string with constructor arguments
  6.     )
  7. );

Which I assumed would also work like this:

  1. $validators = array(
  2.     'name'   => array(
  3.         'Alnum',                
  4.         new Zend_Validate_Alnum(true), //allow whitespaces
  5.        'default' => '',  //meta command 1
  6.        'presence' => 'required', //meta command 2
  7.     )
  8. );

This does not work though. You need to remove the validator type string and replace it with an instance of the Zend_Validate_Alnum validator to get it to accept whitespaces and meta commands. This is the right way to do it:

  1. $validators = array(
  2.     'name'   => array(            
  3.         new Zend_Validate_Alnum(true), //allow whitespaces
  4.        'default' => '', //meta command 1
  5.        'presence' => 'required', //meta command 2
  6.     )
  7. );

The entire script ends up looking like this:

  1.  
  2. $filters = array('name' => 'StringTrim');
  3. $validators =  array(
  4.     'name'   => array(            
  5.         new Zend_Validate_Alnum(true), //allow whitespaces
  6.        'default' => '',
  7.        'presence' => 'required',
  8.     )
  9. );
  10.  
  11. $input = new Zend_Input_Filter($filter, $input, $this->getRequest()->getParams());

Written by Kristian Lunde

July 18th, 2010 at 9:00 pm

Get Adobe Flash player