Noly Labs
Noly Labs

Reputation: 31

custom validator in symfony

I would like create custom validator for Symfony 1.4, for example check length name. I know that it exist, but i would like own.

I create /myapp/lib/validator/sfValidatorName.class.php

Must be there:

class sfValidatorName extends sfValidatorBase
{

  protected function configure($options = array(),
                                $messages = array()) {

      $this->addMessage('invalid', 'Invalid name!');
  }

  protected function doClean($value) {

  }
}

and how can i add for this my function, for example:

    if (count($letters) < 3) {
        return 'too small';
    } else if (count($letters) > 43) {
        return 'too long'; 
    } 

Upvotes: 3

Views: 3112

Answers (2)

Jeremy Kauffman
Jeremy Kauffman

Reputation: 10403

  1. Open /lib/validator/sfValidatorString.class.php
  2. Model your validator after that one.

Upvotes: 2

Gerry
Gerry

Reputation: 6012

Since your example is exactly what sfValidatorString does, why don't you go look at it's source? Basically you just throw a validation error with the relevant error code (eg. invalid, min_length, max_length, ...).

By default any validator has the errors 'invalid' and 'required', but you can add your own with addMessage().

For this specific example, a much smarter choice is to configure or extend sfValidatorString.

Upvotes: 1

Related Questions