Conditional Form Validation

Discussion in 'Customization & add-ons' started by cpaprotna, Jun 20, 2014.

  1. cpaprotna

    cpaprotna Member

    Joined:
    Dec 23, 2013
    Messages:
    44
    I am wondering how to use HTML_QuickForm to add conditional validation to a field.

    I have a checkbox:
    Code:
    $t = $this->addCheckbox('website', $websitedata)->setLabel("Display Website");        
    and a text box:
    Code:
            $t = $this->addText('websitelink', array('size'=>50,'value'=>$data_array['websitelink']))->setLabel("Website URL");
    I added the following rule to the form:
    Code:
            $this->addRule('callback2','--form error--', array($this,'website_check'));
    And here is my callback function:
    Code:
        function website_check($val)
        {       
            $website = $val['website'];
            $websitelink = $val['websitelink'];
            if (!empty($website) ) {
                return ___('Please enter a website link value.');
            } elseif(!empty($websitelink)) {       
                return ___('If you want to display a website on our site, you must check the box to purchase the website link.');
            } else {
                return false;
            }
        }
    The function executes and returns the correct value, but I don't know how to tie the error message to the websitelink field. If I don't tie the rule to the websitelink field, then I don't get the value of the checkbox sent to the callback. If I tie the rule to the form, I'm not sure how to display the error message near the websitelink field.

    Any help is appreciated.
  2. cpaprotna

    cpaprotna Member

    Joined:
    Dec 23, 2013
    Messages:
    44
    I figured this out...
    $web is my checkbox and $t is the field that must contain a value if $web is checked.
    Code:
    $web->addRule('length', '', array(1, 10))->and_($t->addRule('nonempty', 'Websitelink is required'));
    

Share This Page