How to validate digits when using Zend Framework addElement

687 Views Asked by At

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:
3

There are 3 best solutions below

0
Kamal Soni On BEST ANSWER

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.

0
Daniel Gadawski On

There's no such validator as "Num" (or Zend_Validate_Num), try to use "Digits" instead.

0
Gaurav Sharma On

Only regex validator is enough for you. Please use the below regax.You did not need to add extra num validator.

^(+\d{1,2}\s)?(?\d{3})?[\s.-]\d{3}[\s.-]\d{4}$ Matches the following

123-456-7890 (123) 456-7890 123 456 7890 123.456.7890 +91 (123) 456-7890

Hopefully, it will help.