June 09, 2014

9:14 am
In this tutorial, we are going to discuss about How to check the existing email address in database in zend form. If you are creating a user registration form, you will either want to check if a username or an email address is already exist in the database. This is very easy to do, assuming you are familiar with using Zend_Form:

$validator = new Zend_Validate_Db_NoRecordExists('user', 'email'); // user is the table name, and email is the column
    $validator->setMessage("Error: The e-mail has already been registered"); // set your own error message
    $this->addElement('text', 'email', array(
       'label' => 'E-mail Address',
       'required' => true,
       'filters' => array('StringTrim'),
       'validators' => array(
           'EmailAddress',
           $validator
       )
));

That's all.

NOTE: This might be obvious but you cannot chain the setMessage(…) function directly to the end of new Zend_Validate_Db_NoRecordExists('user', 'email');

If you are not familiar Zend_Form, here's a full example:

/* application/forms/Register.php */
class Default_Form_Register extends Zend_Form {
public function init($options = null) {
$this->setMethod('post');
$this->addElement('text', 'firstName', array(
'label' => 'First Name',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
array('validator' => 'StringLength', 'options' => array(1, 255))
)
));
$this->addElement('text', 'lastName', array(
'label' => 'Last Name',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
array('validator' => 'StringLength', 'options' => array(1, 255))
)
));

        $validator = new Zend_Validate_Db_NoRecordExists('user', 'email');
$validator->setMessage("Error: The e-mail has already been registered");
$this->addElement('text', 'email', array(
'label' => 'E-mail Address',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
'EmailAddress',
$validator
)
));

$password = $this->addElement('password', 'password', array(
'filters' => array('StringTrim'),
'validators' => array(
array('StringLength', false, array(8, 20)),
),
'required' => true,
'label' => 'Password',
'id' => 'password'
));

$register = $this->addElement('submit', 'register', array(
'required' => false,
'ignore' => true,
'label' => 'Register Now',
));
}

0 comments:

Post a comment