Creating a Custom Form Filter for Zend_Form - Postcode Filter

Creating a Custom Form Filter for Zend_Form - Postcode Filter

Zend Framework 1 has some excellent filters for making sure the input from a form is what you want. That said there are going to be times when creating your own filter is a must, this happened to me the other day as we needed a way to reformat UK postcodes and make sure we had a standard format in the database. Criteria for postcodes was:

  • all letters to be uppercase
  • all whitespace be removed
  • space inserted between the out code and the in code parts

With the criteria down we can set to in writing our filter, this is not as difficult as it may sound as all we do is write a class which implements the Zend_Filter_Interface like:

class App_Filter_Postcode implements Zend_Filter_Interface
{
    
}

So to make our filter useful we have to add at least one method which is defined by the filter interface, this is called 'filter' and we will add all our code in this method and return the result like so:

class App_Filter_Postcode implements Zend_Filter_Interface
{
    /**
     * Defined by Zend_Filter_Interface.
     *
     * @param string $value
     * @return string
     */
    public function filter($value)
    {
        // make it upper case
        $new = strtoupper($value);

        // remove all spaces
        $new = str_replace(' ', '', $new);

       // get the last 3 characters and add a space before them.
       $replace = substr($new, -3, 3);
       $new = str_replace($replace, ' ' . $replace, $new);

       return $new;
    }
}



14/04/2014 09:50:00 Shaun Freeman Filed Under: Zend Framework PHP, Zend Framework

Twitter Feed
Shaun Freeman @Zendmaster

Shaun Freeman @Zendmaster

I liked a @YouTube video https://t.co/lSFWmpHTX1 Patrick Stewart talks about meeting Sting on the set of DUNE (Funny to the EXTREME)

Shaun Freeman @Zendmaster

I added a video to a @YouTube playlist https://t.co/pmXSmod4ti Anonymous - This will Change Everything You Know... (2018-2019)

Shaun Freeman @Zendmaster

I added a video to a @YouTube playlist https://t.co/GkwTCvBfes Will Artificial Intelligence Take Over The World?

Shaun Freeman @Zendmaster

I liked a @YouTube video https://t.co/Y1ulafmsC6 Frank Abagnale: "Catch Me If You Can" | Talks at Google

Shaun Freeman @Zendmaster

I liked a @YouTube video https://t.co/NBdW2xFnqD ETS2: Special Transport DLC Trailer