zend-frameworksocialengine

How to validate digits when using Zend Framework addElement


I want to add a validator to the form element when adding it to the form by passing 'validator' sub-arrays to the function so that only digits are accepted for phone number.

    class User_Form_Signup_Phone extends Engine_Form {
    public function init() {
        $settings = Engine_Api::_()->getApi('settings', 'core');

        $this->addElement('Text', 'phone', array(
            'label' => 'Phone Number',
            'description' => $description,
            'required' => true,
            'allowEmpty' => false,
            'validators' => array(
                array('NotEmpty', true),
                array('Num', true),
                array('StringLength', true, array(10, 11)),
                array('Regex', true, array('/^[0-9]+$/i')),
            ),
//            'tabindex' => $tabIndex++,
                //'onblur' => 'var el = this; en4.user.checkUsernameTaken(this.value, function(taken){ el.style.marginBottom = taken * 100 + "px" });'
        ));
        $this->phone->getDecorator('Description')->setOptions(array('placement' => 'APPEND', 'escape' => false));
        $this->phone->getValidator('NotEmpty')->setMessage('Please enter a valid phone number.', 'isEmpty');
        $this->phone->getValidator('Regex')->setMessage('Invalid phone number.', 'regexNotMatch');
        $this->phone->getValidator('Num')->setMessage('Phone number must be numeric.', 'notAlnum');

   }
  }

I get the following error:

2018-08-13T11:58:19+00:00 CRIT (2): Zend_Loader_PluginLoader_Exception: Plugin by name 'Num' was not found in the registry; used paths:

Solution

  • You don't require the below lines which is giving you the error.

    array('Num', true),
    

    $this->phone->getValidator('Num')->setMessage('Phone number must be numeric.', 'notAlnum');

    as you are using the regex validator

    array('Regex', true, array('/^[0-9]+$/i')),
    

    The 'Regex' validator would only validate if the numbers are between 0 to 9 and your 'StringLength' validator would validate the required length needed to be a valid phone number.

    As pointed out by Daniel in the other answer the 'Num' validator doesn't exist in Zend.