Question

Is it possible to add new validators during validation chain being executed based on user input?

Example: Lets say we have form with radio select which specifies number of inputs in range 1..10.

<label><input type="radio" name="number" id="number-1" value="1">1</label>
[...]
<label><input type="radio" name="number" id="number-10" value="10">10</label>

After this field there are 10 text inputs with no "notEmpty" validators, which are hidden with jquery until user clicks one of the radios, so in case user will choose 1 instead of 5 or 10, the form will validate.

My question is, can I somehow set validators to specified text inputs based on chosen radio value, during validation of radio field, for example in my custom validator for that field.

My former idea was to create custom validator and apply it to each of text inputs.

Was it helpful?

Solution

Yes you can, but you need to define which radio selection has which validators.

Maybe in your Action or directly in your Zend_Form.

You can overwrite the isValid() Method in your Form, example given.

Or, check for the value of the radio first, after that addValidator() to your form element.

Example

$form = new Application_Form_Test();

$radio = $this->_getParam('radio','default_value');

if($radio=='default_value') {
    $form->myfieldid->addValidator('NotEmpty');
}

if($form->isValid($this->getRequest()->getPost())) {
    //valid form!
}

OTHER TIPS

Set your <input> fields to have a consistent naming scheme like your radio buttons. Then try something like:

$(":radio").on("click", function() {

    var textInputName = $(this).id + "text";

    //Perform validation

});

The idea here would be that your text inputs would be named like <input type="text" id="number-1text" /> etc. so that you could easily call the right one using the above code by associating it with the id of the clicked radio button.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top