Working with zend-validator

January 30, 2018

You need validate your form data before saving them in database. Zendframework has zend-validator component to validate the form input.

We will see how to use validator do some validation tasks
To validate the email field in form you can use following code inside the action in your controller

           $email= $this->params()->fromPost('name');
           $emailValdator=new \Zend\Validator\EmailAddress();
           if ($emailValdator->isValid($email)) {
                  // email is valid
           }else{
           	  echo "Invalid Email";
                  // you can get the default error messages in array format
                  print_r($emailValdator->getMessages());
           }

How to set custom error messages
You can set yourown messages to the validator

           $email= $this->params()->fromPost('name');
           $emailValdator=new \Zend\Validator\EmailAddress();
           // You can set your custom message here
           $emailValdator->setMessage("What you entered is not an email");
           if ($emailValdator->isValid($email)) {

           }else{
           	  
           	 echo  current($emailValdator->getMessages());
           }

Reference
Zend Validators Document