Friday, July 8, 2011

How to use the Filter Validator in Yii

Here's a quick example on how to use the Filter Validator in Yii.

The filter validator isn't actually a validator, it's a filter :) You give it a php function name to run, and it will run that function on the value of the attribute, when validate() is called.
class Address extends CFormModel /* or CActiveRecord */
{
  public $postal_code;
  public $street;

  public function rules()
  {
    return array(
 //call trim() when validate() is called
 array('street', 'filter', 'filter'=>'trim'),

 /* call my custom function filterPostalCode when validate() is called
  * you can pass it any callback function, but it should only have one parameter
  */
 array('postal_code', 'filter', 'filter'=>array( $this, 'filterPostalCode' )),

 /* if you are going to filter, then you should put the required validator last, as the validators are called in order */
 array('postal_code, street', 'required'),
    );
  }

  public function filterPostalCode($value)
  {
    //strip out non letters and numbers
    $value = preg_replace('/[^A-Za-z0-9]/', '', $value);
    return strtoupper($value);
  }
}
Usage:
$address = new Address;
$address->postal_code ="m5w-1e6";
$address->street = " 123 main street ";
$address->validate();
echo "$address->street $address->postal_code";
$address->postal_code ="/*-*/*-*/-";
$address->street = "     ";
$address->validate();
var_dump($address->errors);
Output:

123 main street M5W1E6
array
  'postal_code' => 
    array
      0 => string 'Postal Code cannot be blank.' (length=28)
  'street' => 
    array
      0 => string 'Street cannot be blank.' (length=23)

3 comments:

  1. Very good and nice explanation. It was really required for me.

    ReplyDelete