0

I want to create a custom validator in Zend.

for e.g. my code:

$txt_state = new Zend_Form_Element_Text('state');
$txt_state->setLabel('State');

$txt_prop = new Zend_Form_Element_Text('pin');
$txt_prop->setLabel('Property');

Now I want that the form must be submitted only if at least one of these 2 elements are not empty.

aditya
  • 302
  • 3
  • 15
Aditya Vijay
  • 231
  • 2
  • 13

2 Answers2

1

you can do it dirty way like this:

if ($this->getRequest()->isPost()) {
    if (is_empty($form->getElement('state')->getValue())) {
        $form->getElement('pin')->setRequired();
    }
    if (is_empty($form->getElement('pin')->getValue())) {
        $form->getElement('state')->setRequired();
    }

   if ($form->isValid()) {
     //redirect to success page 
   } else {
    //do nothing, display errors messages, refill form 
   }
}

or cleaner with extended Zend_Form_Element.

konradwww
  • 693
  • 7
  • 16
  • What is this? I want the default behavior of Zend i.e. if a validation fails, the control returns to form page again with the error message. – Aditya Vijay Nov 09 '12 at 10:28
  • Then additionaly add this code: if ($form->isValid()) { //redirect to success page } else { //do nothing, display errors messages, refill form } – konradwww Nov 09 '12 at 10:50
0

Here you can add custom validation like this in controller.

$state = "YOUR VALUE";

$form->state->setValue($state);
$form->getElement('state')->setRequired();
$form->getElement('state')->addValidator( 'Alpha', true, array( 'messages' => array( 'notAlpha' => "Please enter alphabetic character only in state name.
") ));

$mArr = array('state'=>$state);

if( !$form->isValid($mArr) ){

    $myErrorArray[] = $form->getMessages();

    $is_error = 1;
}

Here $myErrorArray have all error message that you apply on element state.

M Rostami
  • 4,035
  • 1
  • 35
  • 39
Nilesh Gupta
  • 367
  • 1
  • 2