Search code examples
zend-frameworkvalidationcapitalization

Zend Framework: Set a validator for starting letter as Capital


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!


Solution

  • 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)