I've read numerous workarounds for Zend Framework's lack of default checkbox validation.
I have recently started using ZF2 and the documentation is a bit lacking out there.
Can someone please demonstrate how I can validate a checkbox to ensure it was ticked, using the Zend Form and Validation mechanism? I'm using the array configuration for my Forms (using the default set-up found in the example app on the ZF website).
Try this
Form element :
In filters, add digit validation
Very old question, but figured it might still be used/referenced by people, like me, still using Zend Framework 2. (Using ZF 2.5.3 in my case)
Jeff's answer above helped me out getting the right config here for what I'm using. In my use case I require the Checkbox, though leaving it empty will count as a 'false' value, which is allowed. His answer helped me allow the
false
values, especially his:The use case is to enable/disable certain entities, such as Countries or Languages so they won't show up in a
getEnabled[...]()
Repository function.Form element
Input filter
This isn't directly related to the question, but here's some zf2 checkbox tips if you're looking to store a user's response in the database...
'required' => false;
Example element creation in form:
Example input filter spec:
And here's an example if you want to hide some other form fields using bootstrap:
I'm a ZF2 fan, but at the end of the day, you just have to find out what works with it and what doesn't (especially with Forms). Hope this helps somebody!
I had the same problem and did something similar to Optimus Crew's suggestion but used the Identical Validator.
If you don't set the
checked_value
option of the checkbox and leave it as the default it should pass in a '1' when the data is POSTed. You can set it if you require, but make sure you're checking for the same value in thetoken
option of the validator.This won't work if you use the option
'use_hidden_element' => false
for the checkbox for the form. If you do this, you'll end up displaying the default NotEmpty messageValue is required and can't be empty
You could also just drop the hidden form field (which I find a bit weird from a purist HTML point of view) from the options instead of setting its value to 'no' like this: