简体   繁体   中英

Custom Zend Validator

I want to create a custom validator in Zend.

for eg 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM