3

For my school project, I try to make a form in Zend.

I would like to insert a Validator that the first letter has to be a Capital letter.

What should I change in this piece of code to make this work?

        $voornaam = $this->createElement('text', 'voornaam');
    $voornaam->setLabel('Voornaam:')
            ->setAttrib('size', 50)->addValidator('StringLength', false,array(2,30))
                ->setRequired(true);

If anyone could help me with this, thanks in advance!

JorritK
  • 75
  • 1
  • 2
  • 9
  • I'm afraid there is not such validator by default. You will have to create your own validator class and add this to your form element. – Fidi Jul 13 '11 at 14:34

2 Answers2

3

Maybe this custom validator will be helpful:

class My_Validate_FirstCapital extends Zend_Validate_Abstract {

    const CAPITAL = 'capital';

    protected $_messageTemplates = array(
        self::CAPITAL => "First letter is not capital"
    );

    public function isValid($value, $context = null) {            

        if ($value != ucfirst($value)) {
            $this->_error(self::CAPITAL);
            return false;
        }

        return true;
    }    
}

I didn't test it, but is should work.

Another way would be to use Zend_Validate_Regex, e.g.

//match first capital letter
$validator = new Zend_Validate_Regex(array('pattern' => '/^[A-Z]/'));
// and add it to your element, ->addValidator($validator)
Marcin
  • 215,873
  • 14
  • 235
  • 294
  • I tried the first answer, because It would be the best solution. I put it before my Class where it should be used. When filling my form and hitting submit, I don't get any error's. What should I do more to make it work? Zend_Validate_Regex solutions works like a charm – JorritK Jul 13 '11 at 15:19
  • @JorritK. you create new validator `$v = new My_Validate_FirstCapital();` and then add it to your element (like for Zend_Validate_Regex). – Marcin Jul 13 '11 at 15:27
  • Works absolutely great, I can not vote up yet, but as soon as I can I will. Thanks a lot! :D – JorritK Jul 13 '11 at 15:36
  • @JorritK. Glad I could help. You can accept the answer. This will also give you some points. – Marcin Jul 13 '11 at 15:38
0

You can always use the regex validiator for things like this. I am little busy so please feel free to step in and provide a complete code example.

Oh, somebody just did

Adrian World
  • 3,118
  • 2
  • 16
  • 25