1

I'm building a form with input filters and all in Zend Framework 2. I'm using arrays to configure my inputs and filters and validators. So, say I have some input:

array(
    'name' => 'foo',
    'required' => true,
)

On the page, there's some jQuery code that might optionally hide this input. If it does, it hides and disables the input. On submit, var_dump on the form data gives foo => null (probably because it didn't actually submit in the post data and so the form input is never given a value). If the input is not hidden and not filled out then on submit it has foo => string '' (length=0).

I want to require the input to have a value if the input is used. So, are there some settings I can add to my config array that will allow null to pass validation, but reject the empty string value? Or do I need to write a custom validator?

1 Answer 1

3

Yes, you ought to use NotEmpty validator.

$inputFilter = new \Zend\InputFilter\InputFilter ();
$inputFilter->add ([
  'name' => 'foo',
  'validators' => [
    [
      'name' => 'not_empty',
      'options' => [
        'type' => 'string'
      ]
    ]
  ]
]);

$form->setInputFilter ($inputFilter);
Sign up to request clarification or add additional context in comments.

1 Comment

For the sake of other readers, the key here is that if you don't specify your own not_empty validator, a default one is created that is more limiting. I eventually got my use-case to work. A couple other keys points here was that I needed to still specify the required attribute (otherwise it seems to assume that it is required?). Also, I had a StringLength validator on there as well, and that had a problem when the input was null, so I had to drop that. Haven't investigated whether I can make StringLength ok with a null value yet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.