Snippets

Create an account or login to be able to add, comment and rate snippets.

Navigation

Refine Tags

Snippets tagged "validator" Snippets tagged "validator"

sfCustomUniqueValidator:

This snippet allow to check if an entry allready exists in a database but, at the difference of the sfUniqueValidator, you can provide as many fields as desired to perform the verification.

Installation:

The first thing you need to do is to create the file sfCustomUniqueValidator.php in your project lib directory:

<?php
  /**
 * sfCustomUniqueValidator checks if a record exist in the database with all the mentionned fields.
 *
 * ex: Check if a companie with company_name exist in country_id 
 *   class:            sfCustomUniqueValidator
 *   param:
 *     class:          Companies    //the class on which the search is performed
 *     nb_fields:      2            //the number of fields on which the comparison is done
 *     field_1:        company_name //First field of the comparison
 *     field_2:        country_id   //Other country for the comparison
 *
 * @package    lib
 * @author     Joachim Martin
 * @date       15/06/2007
 */
 
class sfCustomUniqueValidator extends sfValidator {
 
   /**
   * Executes this validator.
   *
   * @param mixed A file or parameter value/array
   * @param error An error message reference
   *
   * @return bool true, if this validator executes successfully, otherwise false
   */
 
    public function execute(&$value, &$error) {
 
        $className  = $this->getParameter('class').'Peer';
 
        //Get fields number
        $nb_fields = $this->getParameter('nb_fields');
 
        //Define new criteria       
        $c = new Criteria();
 
        //Loop on the fields
        for($i = 1; $i <= $nb_fields ; $i++) {
            //Retrieve field_$i 
            $check_param = $this->getParameterHolder()->get("field_$i");
            $check_value = $this->getContext()->getRequest()->getParameter($check_param);
 
            //If check value defined        
            if ($check_value != '') {   
                //Adding field to the criteria
                $columnName = call_user_func(array($className, 'translateFieldName'), $check_param, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_COLNAME);
                $c->add($columnName, $check_value);
            }
        }
 
        $object = call_user_func(array($className, 'doSelectOne'), $c);
 
        if ($object)
        {
          $tableMap = call_user_func(array($className, 'getTableMap'));
          foreach ($tableMap->getColumns() as $column)
          {
            if (!$column->isPrimaryKey())
            {
              continue;
            }
 
            $method = 'get'.$column->getPhpName();
            $primaryKey = call_user_func(array($className, 'translateFieldName'), $column->getPhpName(), BasePeer::TYPE_PHPNAME, BasePeer::TYPE_FIELDNAME);
            if ($object->$method() != $this->getContext()->getRequest()->getParameter($primaryKey))
            {
              $error = $this->getParameter('custom_unique_error');
 
              return false;
            }
          }
        }
 
        return true;
    } 
 
    public function initialize ($context, $parameters = null) {
        // initialize parent
        parent::initialize($context);
 
        //Set default parameters value
        $this->setParameter('custom_unique_error','The value is not unique');
 
        $this->getParameterHolder()->add($parameters);
 
        // check parameters
        if (!$this->getParameter('class'))
        {
          throw new sfValidatorException('The "class" parameter is mandatory for the sfCustomUniqueValidator validator.');
        }
 
        if (!$this->getParameter('nb_fields'))
        {
          throw new sfValidatorException('The "nb_fields" parameter is mandatory for the sfCustomUniqueValidator validator.');
        }
 
        return true;
    }
}

Usage:

The following code check if a companie with the same name and same activity exists in the same country

sfCustomUniqueValidator:
      class:                   Companies
      nb_fields:               3
      field_1:                 company_name
      field_2:                 activity_id
      field_3:                 country_id
      custom_unique_error:     This company already exist for this country

class: the model to test

nb_fields: how many fields will be checked

field_x: a field to test, obviously you need to have as many field_x as the nb_fields value

custom_unique_error: your error message

This is my very first contribution to symfony so feel free to comment/optimize.

by joachim martin on 2007-06-21, tagged unique  validation  validator 
(5 comments)

sfFileImageValidator

Description:

This images validations is an extention for the sfFileValidator. You can use it for validate uploaded images maximum width and height, minimum width and height and if the images have square dimensions.

<?php
 
/**
 * sfFileImageValidator allows you to apply constraints to image file upload, it extend the sfFileValidator functions.
 *
 * <b>Optional parameters:</b>
 *
 * # <b>max_height</b>         - [none]                                - Maximum images height in pixels.
 * # <b>max_height_error</b>   - [The file height is too large]        - An error message to use when
 *                                                                       images height is too large.
 * # <b>max_width</b>          - [none]                                - Maximum images width in pixels.
 * # <b>max_width_error</b>    - [The file width is too large]         - An error message to use when
 *                                                                       images width is too large.
 * # <b>min_height</b>         - [none]                                - Minimum images height in pixels.
 * # <b>min_height_error</b>   - [The file height is too small]        - An error message to use when
 *                                                                       images height is too small.
 * # <b>min_width</b>          - [none]                                - Minimum images width in pixels.
 * # <b>min_width_error</b>    - [The file width is too small]         - An error message to use when
 *                                                                       images width is too small.
 * # <b>is_square</b>          - [false]                               - The image is a square
 * # <b>is_square_error</b>    - [The file is not a square]            - An error message to use when
 *                                                                       the images is not a square
 *                                                                       (The width size is not equal
 *                                                                       to the height size).
 * @package    symfony
 * @subpackage validator
 * @author     Daniel Santiago 
 */
 
class sfFileImageValidator extends sfFileValidator
{
  /**
   * Executes this validator.
   *
   * @param mixed A file or parameter value/array
   * @param error An error message reference
   *
   * @return bool true, if this validator executes successfully, otherwise false
   */
 
  public function execute(&$value, &$error)
  {
    if (parent::execute($value, $error))
    {
      list($width, $height) = @getimagesize($value['tmp_name']);
 
      // File is not a square
      $is_square = $this->getParameter('is_square');
      if ($is_square && $width != $height)
      {
        $error = $this->getParameter('is_square_error');
 
        return false;
      }
 
      // File height too large
      $max_height = $this->getParameter('max_height');
      if ($max_height !== null && $max_height < $height)
      {
        $error = $this->getParameter('max_height_error');
 
        return false;
      }
 
      // File width too large
      $max_width = $this->getParameter('max_width');
      if ($max_width !== null && $max_width < $width)
      {
        $error = $this->getParameter('max_width_error');
 
        return false;
      }
 
      // File height too small
      $min_height = $this->getParameter('min_height');
      if ($min_height !== null && $min_height > $height)
      {
        $error = $this->getParameter('min_height_error');
 
        return false;
      }
 
      // File width too small
      $min_width = $this->getParameter('min_width');
      if ($min_width !== null && $min_width > $width)
      {
        $error = $this->getParameter('min_width_error');
 
        return false;
      }
 
      return true;
    }
  }
 
  /**
   * Initializes this validator.
   *
   * @param sfContext The current application context
   * @param array   An associative array of initialization parameters
   *
   * @return bool true, if initialization completes successfully, otherwise false
   */
  public function initialize($context, $parameters = null)
  {
    // initialize parent
    parent::initialize($context, $parameters);
 
    // set defaults
    $this->getParameterHolder()->set('max_height',        null);
    $this->getParameterHolder()->set('max_height_error',  'The file height is too large');
    $this->getParameterHolder()->set('max_width',         null);
    $this->getParameterHolder()->set('max_width_error',   'The file width is too large');
    $this->getParameterHolder()->set('min_height',        null);
    $this->getParameterHolder()->set('min_height_error',  'The file height is too small');
    $this->getParameterHolder()->set('min_width',         null);
    $this->getParameterHolder()->set('min_width_error',   'The file width is too small');
    $this->getParameterHolder()->set('is_square',         false);
    $this->getParameterHolder()->set('is_square_error',   'The file is not a square');
 
    $this->getParameterHolder()->add($parameters);
 
    return true;
  }
}
 

How to use it?

In the YAML validation file put this:

  news{photo}:
    file:     yes
    sfFileImageValidator:
      min_height:       100
      min_height_error: 'The image height is too small, it must have minimum 100px'
      min_width:        120
      min_width_error: 'The image width is too small, it must have minimum 120px'
      max_height:       960
      max_height_error: 'The image height is too large, it must have maximum 960px'
      max_width:        450
      max_width_error: 'The image width is too large, it must have maximum 450px'
      is_square:        true
      is_square_error:  'The images must be a square (The height be equal to the width)'
 
      max_size:         256000
      max_size_error:   'The maximum images size is 250Kb'
      mime_types_error: 'We only accept GIF, PNG and JPEG.'
      mime_types:
        - 'image/jpeg'
        - 'image/png'
        - 'image/gif'
 
by Daniel Santiago on 2007-12-26, tagged image  images  validation  validator 

Login form in Symfony 1.1, with the new form system

Symfony 1.1 comes with a complete new form system. It works completely according to the MVC draft:

Make sure you have a running Symfony 1.1 based project and application and modules. In this example I build the form inside the myModule module and myLogin action.

My form makes use of i18n, which is in my case autoloaded in settings.yml.

This tutorial uses Symfony 1.1 beta4 and RC1. There are a little important changes with respect to beta3, which I don't cover.

I also expect you to have practical knowledge and a little bit experience with Symfony as system. I will not explain how you i18n implements or modules shield with security.yml.

The form design

The form gets two import fields: username and password. Furthermore is there a hidden field in which the URI comes that the user requested, but got redirected to the loginform (through Symfony’s security.yml and settings.yml). This will be used to go to that URI again after a successful login.

Both imput fields are required I will build a custom validation for a correct username/password check. Also we want to make use of a little new protection feature: CSRF.

The form takes uses i18n for multilinguity, I will use English primarily, but the view has been prepared for other languages.

The start: the action

We will begin with the action which contains the primary control.

/**
 * Executes myLogin action
 *
 * Login functionality.
 *
 * @param void
 * @return void
 * @access public
 */
public function executeMyLogin() {
   // Erase auth data
   $this->getUser()->clearCredentials();
   $this->getUser()->setAuthenticated(FALSE);
 
   // Build login form
   $oForm = new inloggenForm();
 
   if ($this->getRequest()->isMethod('post')) { // When called through POST (form submit)
       $oForm->bind(
           array('username' => $this->getRequest()->getParameter('username'),
                 'password' => $this->getRequest()->getParameter('password'),
                 'referrer' => $this->getRequest()->getParameter('referrer'),
                )
      );
 
      // Save orginal requested location in referrer field
      $oForm->setDefault('referrer', $this->getRequest()->getParameter('referrer'));
      if ($oForm->isValid()) { // When validations OK
          $aValues = $oForm->getValues();
          sfContext::getInstance()->getLogger()->debug($aValues['username']);
 
          // Authentification
          $this->getUser()->setAuthenticated(TRUE);
 
          // To requested page
          $this->redirect($this->getRequest()->getParameter('referrer'));
      }
   } else {
      // Save original requested uri in form
      $oForm->setDefault('referrer', sfContext::getInstance()->getRequest()->getUri());
   }
 
   $this->oForm = $oForm; // form to view
}
 

Logic of authentification is set after POST further. Through the sfForm::bind() method couples the input of the user coupled with the form controller.

The form controller

I made this in myModule/lib/form/inloggenForm.class.php. In the form is defined and coupled with the validations and the formatting.

<?php
class inloggenForm extends sfForm {
    /**
     * Prepare validators
     */
    private function _setValidators() {
        $this->oValGebruikersnaam = new sfValidatorAnd(
                                    array(
                                        new sfValidatorString(array('min_length' => 3, 'max_length' => 50),
                                                              array('min_length' => 'The username should be at least three characters long',
                                                                    'max_length' => 'The username should be fifty characters long at most',
                                                              )
                                        ),
                                        new sfValidatorCallback(array('callback'  => array('cmsLoginValidator', 'execute'),
                                                                      'arguments' => array()
                                                                ),
                                                                array('invalid'  => 'This username/password combination is unknown')
                                        ),
                                    ),
                                    array('required'   => TRUE),
                                    array('required'   => 'The username is mandatory')
        );
        $this->oValWachtwoord = new sfValidatorString(array('required' => TRUE),
                                                      array('required'   => 'The password is mandatory')
        );
        $this->oValReferrer = new sfValidatorString(array('required' => FALSE));
    }
 
    /**
     * Prepare widgets
     */
    private function _setWidgets() {
        $this->oWidGebruikersnaam = new sfWidgetFormInput(array(), array('id' => 'username', 'size' => 25));
        $this->oWidWachtwoord     = new sfWidgetFormInputPassword(array(), array('id' => 'password', 'size' => 10));
        $this->oWidReferrer       = new sfWidgetFormInputHidden(array(), array('id' => 'referrer'));
    }
 
    /**
     * Configure form
     */
    public function configure()     {
        $this->_setValidators();
        $this->_setWidgets();
 
        /*
         * Set validators
         */
        $this->setValidators(array('username' => $this->oValGebruikersnaam,
                                   'password'     => $this->oValWachtwoord,
                                   'referrer'       => $this->oValReferrer,
                             )
        );
 
        /*
         * Set widgets
         */
        $this->setWidgets(array('username' => $this->oWidGebruikersnaam,
                                'password'     => $this->oWidWachtwoord,
                                'referrer'       => $this->oWidReferrer,
                          )
        );
 
        /*
         * Set decorator
         */
        $oDecorator = new sfWidgetFormSchemaFormatterDiv($this->getWidgetSchema());
        $this->getWidgetSchema()->addFormFormatter('div', $oDecorator);
        $this->getWidgetSchema()->setFormFormatterName('div');
        $this->getWidgetSchema()->setHelps(array('username' => 'Please enter your username',
                                                 'password' => 'Please enter your password'
                                           )
        );
 
    }
 
    /**
     * Bind override
     */
    public function bind(array $taintedValues = null, array $taintedFiles = array()) {
        $request = sfContext::getInstance()->getRequest();
 
        if ($request->hasParameter(self::$CSRFFieldName))         {
            $taintedValues[self::$CSRFFieldName] = $request->getParameter(self::$CSRFFieldName);
        }
 
        parent::bind($taintedValues, $taintedFiles);
    }
}
 

There are two private methods:

I overloaded the earlier mentioned bind() method to process the CSRF token internally. This fiels is regulated by sfForm internally, you to do need to worry about it much, only with the actual functionality.

The configure() method contains the functionality. The validators are created and linked to the corresponding fields and also are the widgets. Also, the decorator is defined with I will go into later on.

Validators

In _setValidators() sfValidatorBase objects are made for each field.

The password field check is the simplest, only the required input is checked. The object is of the type sfValidatorString (extend sfValidatorBase) without extra controls, only the required attribute with errortext is specified. In principle, you can use each validator as -empty- container.

The username is a combination; it is required, there are restrictions to the the stringlength and a correct login is checked. The stringcontrole/requirement is checked through sfValidatorString, which is quite simple.

The check for a correct login is done through a special validator, that does a callback to an custom function: sfValidatorCallback. This is explained later.

Since these two validators check the same field , the sfValidatorAnd validator is used that combines several validators. All validators must be satisfied. Of course Symfony also offers sfValidatorOr that checks that at least one underlying validator satisfies.

The custom logincheck

As you can see the callback validator calls to a custom class/method: myLoginValidator::execute().

/**
 * Fiel with myLoginValidator klasse
 *
 * @package -
 */
/**
 * Validation correct username/password
 *
 * @author Jordi Backx (Snowkrash)
 * @copyright Copyright © 2008, Jordi Backx (Snowkrash)
 * @package -
 */
class myLoginValidator {
    /**
     * execute validator
     *
     * @param sfValidatorBase Validator instance that calls this method
     * @param string Value of field that sfValidatorCallback checks
     * @param array Arguments for correct working
     *
     * @return value field when OK. Nothing if error (sfValidatorError exception)
     */
    public static function execute ($oValidator, $sValue, $aArguments) {
        if ( /* check OK */ ) { // Return waarde veld indien controle OK
            return $sValue;
        }
        // Throw exception when not OK
        throw new sfValidatorError($oValidator, 'invalid', array('value' => $sValue, 'invalid' => $oValidator->getOption('invalid')));
    }
}
 

I set this here with no further logic, that is application specific, thus that you 'll have to do yourself. The base structure can be used. The three parameters must be defined, otherwise the whole application crashes.

Widgets

In _setWidget() sfWidget objects are made for each field.

The widgets are the form elements: finally <input>, <select> etc tags in combination with labels and errortexts.

Each widget can have HTML attributes, which will be printed inside the form elements.

The view

Finally the form must be printed to the screen through a view template.

<p><?php echo __('You need to log in to be able to use the Content Management System.') ?></p>
<div id="formContainer">
<?php if ($oForm->getErrorSchema()->getErrors()) { ?>
    <div id="formulierFouten">
    <ul>
    <?php foreach ($oForm->getErrorSchema() as $sError) { ?>
        <li><?php echo __($sError) ?></li>
    <?php } ?>
    </ul>
    </div>
<?php } ?>
<form action="<?php echo url_for('myModule/myLogin') ?>" method="post">
    <?php echo $oForm['username']->renderLabel(__($oForm['username']->renderLabelName())); echo $oForm['username']->renderRow(__($oForm->getWidgetSchema()->getHelp('username'))); ?>
    <?php echo $oForm['password']->renderLabel(__($oForm['password']->renderLabelName())); echo $oForm['password']->renderRow(__($oForm->getWidgetSchema()->getHelp('password'))); ?>
    <?php echo $oForm['referrer']->render(array('value' => $oForm->getDefault('referrer'))) ?>
    <?php echo $oForm['_csrf_token'] ?>
    <label for="inloggen">&nbsp;</label><input type="submit" value="Inloggen" id="inloggen" class="aanmeldenSubmit" />
</form>
</div>
 

You can see all the i18n code (__() helper) and some non-Symfony 1.0 form building. Errorlists are built through the errorSchema which is available within the form object, the texts themself can be translated as you can see.

Also the labels and help texts are squeezed through i18n. The field names are in English, because the labels are based on these and must go through i18n. This way everything can be translated.

You can print the whole form with an echo of $oForm (goes through __toString()), but you have more control over the layout when you use specific widgetrender functions, like I do with renderRow(). This method takes the helptext as an argument, with is also translated.

The submit button is no widget, so we place it ourselves the old-fashioned way ... no helper, that is so Symfony 1.0.

CSRF token

That one is new. It is there, but we never defined it. It is created within sfForm and only since beta4 when indicated in settings.yml:

#Form security secret (CSRF protection)
    csrf_secret:             hierjeeigenc0d3     # Unique secret to enable CSRF protection or false to disable
 

You can choose your own code, on which the hash inside the CSRF value is based.

The form functionally is ready, but we want more control over the layout. I am a supporter of the tableless HTML design and the standard formatter of sfForm uses ... tables. Well, we can do better.

The form controller showed the coupling with my own formatter:

/*
 * Set decorator
 */
$oDecorator = new sfWidgetFormSchemaFormatterDiv($this->getWidgetSchema());
$this->getWidgetSchema()->addFormFormatter('div', $oDecorator);
$this->getWidgetSchema()->setFormFormatterName('div');
 

I will now go into this part.

I have a class sfWidgetFormSchemaFormatterDiv in sfWidgetFormSchemaFormatterDiv.class.php made in the application-level lib/ directory so that all modules of can use it.

This takes care of the HTML layout of the form elements.

class sfWidgetFormSchemaFormatterDiv extends sfWidgetFormSchemaFormatter {
    protected
        $rowFormat = '%error%%field%<br />%help%<br />',
        $helpFormat = '<span class="help">%help%</span>',
        $errorRowFormat = '<div>%errors%</div>',
        $errorListFormatInARow = '%errors%',
        $errorRowFormatInARow = '<div class="formError">&darr;&nbsp;%error%&nbsp;&darr;</div>',
        $namedErrorRowFormatInARow = '%name%: %error%<br />',
        $decoratorFormat = '<div id="formContainer">%content%</div>';
}
 

A good article is available that describes this system.

For people that wonder why the label (%label% placeholder) is not used: $rowFormat sets the layout of the renderRow() method and since I want to render the label separately (i18n), it must not be rendered a second time by renderRow().

Conclusion

Hopefully the above can be a good help for your own form in Symfony 1.1. The documentation is quite scarce at the moment, so each bit of help will be welcome.

If the English is somewhat bad, I did a automatic translation of my original Dutch version of the article and tuned that a bit. The reason? I am lazy. ;-)

If you find errors in the above, it is because of copying my code probably. Please mention it in the comments.

Good luck!

by Jordi Backx on 2008-05-10, tagged 11  csrf  decorator  form  formatter  i18n  login  sfform  symfony  validator  widget 

Pass multiple parameters to sfCallbackValidator

I love sfCallbackValidator and use it all the time, but found it was somewhat limiting in that only the value being validated could be passed to the function or method that is doing the validating. So, I've extended it, overriding the execute method:

myCallbackValidator.class.php:

<?php
 
class myCallbackValidator extends sfCallbackValidator {
 
  public function execute(&$value, &$error) {
 
    $callback = $this->getParameterHolder()->get('callback');
    if (!call_user_func($callback, $value, $this->getParameterHolder()->get('parameters'))) {
      $error = $this->getParameterHolder()->get('invalid_error');
      return false;
    }
    return true;
 
  }
 
}

You can specify the parameters in your validation yaml file like so...

  birthdate:
    myCallbackValidator:
      callback:       [myValidationTools, birthDate]
      invalid_error:  Birthdate is invalid. You must be at least 18 years old to apply.
      parameters:
        min_age:      18

And then the parameters can be accessed in the callback function like so:

  public static function birthDate($string, $params = null) {
    if (isset($params['min_age'])) {
      ... etc...
by east3rd on 2007-06-27, tagged callback  validation  validator 
(2 comments)

Credit Card Validator II

Here is another variation on the credit card validator. In your validate/[action].yml file, you can implement this helper like so:

fields:
  cc_type:
    required:
      msg:      Please select a card type
    sfStringValidator:
      values:       [Visa, MasterCard, Discover, American Express]
      values_error: Please select a credit card type
      insensitive:  true
 
  cc_number:
    required:
      msg:      Please provide a credit card number
    myCreditCardValidator:
      card_name: cc_type    # refers to field name in form that contains card type, like Visa, MasteCard, etc.

Place this file, myCreditCardValidator.class.php, in you application's /lib directory and clear the cache.

<?php
 
/**
 * This class has been converted to a Symfony Validator from original code
 * created by John Gardner, 4th January 2005. 
 * http://www.braemoor.co.uk/software/index.shtml
 *
 * Symfony conversion by Scott Meves, Stereo Interactive & Design, 2007
 * http://www.stereointeractive.com
 * 
 * This routine checks the credit card number. The following checks are made:
 * 
 * 1. A number has been provided
 * 2. The number is a right length for the card
 * 3. The number has an appropriate prefix for the card
 * 4. The number has a valid modulus 10 number check digit if required
 * 
 **/
 
class myCreditCardValidator extends sfValidator
{    
 
    static protected $CARDS = array (
        array ('name'           => 'American Express', 
            'length'            => '15', 
            'prefixes'      => '34,37',
            'checkdigit'    => true
    ),
        array ('name'           => 'Carte Blanche', 
               'length'         => '14', 
               'prefixes'   => '300,301,302,303,304,305,36,38',
               'checkdigit' => true
        ),
        array ('name'       => 'Diners Club', 
               'length'         => '14',
               'prefixes'   => '300,301,302,303,304,305,36,38',
               'checkdigit' => true
    ),
        array ('name'       => 'Discover', 
               'length'         => '16', 
               'prefixes'   => '6011',
               'checkdigit' => true
    ),
        array ('name'       => 'Enroute', 
               'length'         => '15', 
               'prefixes'   => '2014,2149',
               'checkdigit' => true
    ),
        array ('name'       => 'JCB', 
               'length'         => '15,16', 
               'prefixes'   => '3,1800,2131',
               'checkdigit' => true
    ),
        array ('name'       => 'Maestro', 
               'length'         => '16', 
               'prefixes'   => '5020,6',
               'checkdigit' => true
    ),
        array ('name'       => 'MasterCard', 
               'length'         => '16', 
               'prefixes'   => '51,52,53,54,55',
               'checkdigit' => true
    ),
        array ('name'       => 'Solo', 
               'length'         => '16,18,19', 
               'prefixes'   => '6334, 6767',
               'checkdigit' => true
    ),
        array ('name'       => 'Switch', 
               'length'         => '16,18,19', 
               'prefixes'   => '4903,4905,4911,4936,564182,633110,6333,6759',
               'checkdigit' => true
    ),
        array ('name'       => 'Visa', 
               'length'         => '13,16', 
               'prefixes'   => '4',
               'checkdigit' => true
    ),
        array ('name'       => 'Visa Electron', 
               'length'         => '16', 
               'prefixes'   => '417500,4917,4913',
               'checkdigit' => true
        )
  );
 
  public function initialize($context, $parameters = null)
  {
    // initialize parent
    parent::initialize($context);
 
    // set defaults
    $parameterHolder = $this->getParameterHolder();
    $parameterHolder->set('cc_error_type',      'Unknown card type');
    $parameterHolder->set('cc_error_missing', 'No card number provided');
    $parameterHolder->set('cc_error_format',    'Credit card number has invalid format');
    $parameterHolder->set('cc_error_number',    'Credit card number is invalid');
    $parameterHolder->set('cc_error_length',    'Credit card number is wrong length');
 
    $this->getParameterHolder()->add($parameters);
 
    return true;
  }
 
  public function execute(&$value, &$error)
  {
    $cardName = $this->getParameterHolder()->get('card_name');
    $cardName = $this->getContext()->getRequest()->getParameter($cardName);
 
    $cardNumber = $value;
 
      // Establish card type
      $cardType = -1;
      for ($i=0; $i<sizeof(self::$CARDS); $i++) 
        {   // See if it is this card (ignoring the case of the string)
        if (strtolower($cardName) == strtolower(self::$CARDS[$i]['name']))
            {
          $cardType = $i;
          break;
        }
      }
 
      // If card type not found, report an error
      if ($cardType == -1) 
        {
            $error = $this->getParameterHolder()->get('cc_error_type');
        return false; 
      }
 
      // Ensure that the user has provided a credit card number
      if (strlen($cardNumber) == 0)
        {
         $error = $this->getParameterHolder()->get('cc_error_missing');
         return false; 
      }
 
      // Remove any non-digits   from the credit card number
      $cardNo = preg_replace('/[^0-9]/', '', $cardNumber);
 
      // Check that the number is numeric and of the right sort of length.
      if (!eregi('^[0-9]{13,19}$',$cardNo))
        {
         $error = $this->getParameterHolder()->get('cc_error_format');
         return false; 
      }
 
      // Now check the modulus 10 check digit - if required
      if (self::$CARDS[$cardType]['checkdigit'])
        {
        $checksum = 0;   // running checksum total
        $mychar = "";    // next char to process
        $j = 1;          // takes value of 1 or 2
 
        // Process each digit one by one starting at the right
        for ($i = strlen($cardNo) - 1; $i >= 0; $i--) 
            {
          // Extract the next digit and multiply by 1 or 2 on alternative digits.      
          $calc = $cardNo{$i} * $j;
 
          // If the result is in two digits add 1 to the checksum total
          if ($calc > 9) {
            $checksum = $checksum + 1;
            $calc = $calc - 10;
          }
 
          // Add the units element to the checksum total
          $checksum = $checksum + $calc;
 
          // Switch the value of j
          if ($j ==1) {$j = 2;} else {$j = 1;};
        } 
 
        // All done - if checksum is divisible by 10, it is a valid modulus 10.
        // If not, report an error.
        if ($checksum % 10 != 0)
            {
            $error = $this->getParameterHolder()->get('cc_error_number');
            return false; 
        }
      }  
 
      // The following are the card-specific checks we undertake.
 
      // Load an array with the valid prefixes for this card
      $prefix = split(',',self::$CARDS[$cardType]['prefixes']);
 
      // Now see if any of them match what we have in the card number  
      $prefixValid = false; 
      for ($i=0; $i<sizeof($prefix); $i++)
        {
        $exp = '^' . $prefix[$i];
        if (ereg($exp,$cardNo))
            {
          $prefixValid = true;
          break;
        }
      }
 
      // If it isn't a valid prefix there's no point at looking at the length
      if (!$prefixValid)
        {
         $error = $this->getParameterHolder()->get('cc_error_number');
         return false; 
      }
 
      // See if the length is valid for this card
      $lengthValid = false;
      $lengths = split(',',self::$CARDS[$cardType]['length']);
      for ($j=0; $j<sizeof($lengths); $j++)
        {
        if (strlen($cardNo) == $lengths[$j])
            {
          $lengthValid = true;
          break;
        }
      }
 
      // See if all is OK by seeing if the length was valid. 
      if (!$lengthValid)
        {
         $error = $this->getParameterHolder()->get('cc_error_length');
         return false; 
      };   
 
      // The credit card is in the required format.
      return true;
  }
}
by scott meves on 2007-04-08, tagged cc  creditcard  validation  validator 

Credit Card validator

sfValidator extension based on Credit Card Validator code by Harish Chauhan (from phpclasses.org). With this extension you can validate this type of credit cards: VISA, MASTERCARD, DISCOVER, AMEX, DINERS,JCB, Australian Bankcard, EnRoute And Switch Solo.

IMHO isn't a bad idea to include anything like this in standard sfValidator code. While here you have the source code of my adaptation of credit cards validator.

<?php
 
/*
 
Symfony integration as sfValidator of CCVAL
Date - Jun 17, 2006
Author - Oriol Rius (oriol@joor.net)
 
Credit CArd Validator
Date - Jan 14, 2005
Author - Harish Chauhan
 
 
ABOUT
This PHP script will calidate credit cards by checking there length
and pattern and checksum using mod 10.
 
Supported credit cards are VISA, MASTERCARD, DISCOVER, AMEX, DINERS,
JCB, Australian Bankcard, EnRoute And Switch Solo.
*/
 
class CCVAL extends sfValidator
{
 
    public function execute (&$value, &$error)
    {       
        // Recuperamos parámetros validar
        $num_param = $this->getParameterHolder()->get('num');
        $num = $this->getContext()->getRequest()->getParameter($num_param);
        $tipo_param = $this->getParameterHolder()->get('tipo');
        $tipo = $this->getContext()->getRequest()->getParameter($tipo_param);
 
        // Lanzamos la validación
        $validada=$this->_isVAlidCreditCard($num,$tipo,false);
 
        // Informamos de como ha ido la validación
        sfContext::getInstance()->getLogger()->info("CCVAL.class.php: Tipo: ".$tipo." Num: ".$num." Validada: ".$validada);             
 
        if ($validada==false)
        {
            $error = $this->getParameterHolder()->get('error');
            return false;
        }
        return true;
    }
 
    public function initialize ($context, $parameters = null)
    {
        // initialize parent
        parent::initialize($context);
 
        $this->getParameterHolder()->add($parameters);
 
        return true;
    }
 
    /**
     * Testing checksum
     *
     * @param integer $ccnum
     * @return boolean
     */
    private function _checkSum($ccnum)
    {
        $checksum = 0;
        for ($i=(2-(strlen($ccnum) % 2)); $i<=strlen($ccnum); $i+=2)
        {
            $checksum += (int)($ccnum{$i-1});
        }
        // Analyze odd digits in even length strings or even digits in odd length strings.
        for ($i=(strlen($ccnum)% 2) + 1; $i<strlen($ccnum); $i+=2)
        {
            $digit = (int)($ccnum{$i-1}) * 2;
            if ($digit < 10)
            { $checksum += $digit; }
            else
            { $checksum += ($digit-9); }
        }
        if (($checksum % 10) == 0)
        return true;
        else
        return false;
 
    }
 
    /**
     * Launch validation
     *
     * @param integer $ccnum
     * @param string $type
     * @param boolean $returnobj
     * @return boolean
     */
    private function _isVAlidCreditCard($ccnum,$type="",$returnobj=false)
    {
        $creditcard=array(  "visa"=>"/^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/",
        "mastercard"=>"/^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/",
        "discover"=>"/^6011-?\d{4}-?\d{4}-?\d{4}$/",
        "amex"=>"/^3[4,7]\d{13}$/",
        "diners"=>"/^3[0,6,8]\d{12}$/",
        "bankcard"=>"/^5610-?\d{4}-?\d{4}-?\d{4}$/",
        "jcb"=>"/^[3088|3096|3112|3158|3337|3528]\d{12}$/",
        "enroute"=>"/^[2014|2149]\d{11}$/",
        "switch"=>"/^[4903|4911|4936|5641|6333|6759|6334|6767]\d{12}$/");
        if(empty($type))
        {
            $match=false;
            foreach($creditcard as $type=>$pattern)
            if(preg_match($pattern,$ccnum)==1)
            {
                $match=true;
                break;
            }
 
            if(!$match)
            return false;
            else
            {
                if($returnobj)
                {
                    $return=new stdclass;
                    $return->valid=$this->_checkSum($ccnum);
                    $return->ccnum=$ccnum;
                    $return->type=$type;
                    return $return;
                }
                else
                return $this->_checkSum($ccnum);
            }
 
        }
        else
        {
            if(@preg_match($creditcard[strtolower(trim($type))],$ccnum)==0)
            return false;
            else
            {
                if($returnobj)
                {
                    $return=new stdclass;
                    $return->valid=$this->_checkSum($ccnum);
                    $return->ccnum=$ccnum;
                    $return->type=$type;
                    return $return;
                }
                else
                return $this->_checkSum($ccnum);
            }
        }
    }
}
?>

An example of how you can call CCVAL validator from validate yml file:

methods:
  post: [ntarjeta]
names:
  ntarjeta:
    required:     Yes
    required_msg: Credit Card number is required
    validators:   validarCC
 
validarCC:
    class:       CCVAL
    param:
      num:       ntarjeta
      tipo:      tipoCC
      error:     Your credit card number is invalid

Sorry for my poor english.

by Oriol Rius on 2006-06-24, tagged cc  validation  validator 

Password Strength validator

This its a password strength validator, with ajax request for checking the password field.

First create a validator in lib/validators/sfPasswordStrengthValidator.class.php

<?php
class sfPasswordStrengthValidator extends sfValidator
{
    public function execute (&$value, &$error)
    {
        $weakness = $this->Password_Strength($value);
 
        if($weakness==1) {
            $error = $this->getParameter('strength_error');
            return false;
        }
 
        return $weakness;
    }
 
    public function initialize ($context, $parameters = null)
    {
        // Initialize parent
        parent::initialize($context);
 
        // Set default parameters value
        $this->setParameter('strength_error', 'Weak password');
 
        // Set parameters
        $this->getParameterHolder()->add($parameters);
 
        return true;
    }
        // Thanks for: Alix Axel Weblog
    // URL: http://www.alixaxel.com/wordpress/wp-content/2007/06/Password_Strength.phps
    function Password_Strength($password, $username = null)
    {
        if (!empty($username))
        {
            $password = str_replace($username, '', $password);
        }
 
        $strength = 0;
        $password_length = strlen($password);
 
        if ($password_length < 5)
        {
            return $strength;
        }
 
        else
        {
            $strength = $password_length * 4;
        }
 
        for ($i = 2; $i <= 4; $i++)
        {
            $temp = str_split($password, $i);
 
            $strength -= (ceil($password_length / $i) - count(array_unique($temp)));
        }
 
        preg_match_all('/[0-9]/', $password, $numbers);
 
        if (!empty($numbers))
        {
            $numbers = count($numbers[0]);
 
            if ($numbers >= 3)
            {
                $strength += 5;
            }
        }
 
        else
        {
            $numbers = 0;
        }
 
        preg_match_all('/[|!@#$%&*\/=?,;.:\-_+~^¨\\\]/', $password, $symbols);
 
        if (!empty($symbols))
        {
            $symbols = count($symbols[0]);
 
            if ($symbols >= 2)
            {
                $strength += 5;
            }
        }
 
        else
        {
            $symbols = 0;
        }
 
        preg_match_all('/[a-z]/', $password, $lowercase_characters);
        preg_match_all('/[A-Z]/', $password, $uppercase_characters);
 
        if (!empty($lowercase_characters))
        {
            $lowercase_characters = count($lowercase_characters[0]);
        }
 
        else
        {
            $lowercase_characters =