Best way to validate that at least one checkbox is checked

Hello,

I have few checkboxes in my form and at least one of them should be checked. Otherweise should come the error message "Please select one checkbox". What is the best way to do it?

Thanks

use Phalcon\Forms\Element\Check;
use Phalcon\Validation\Validator\PresenceOf;

$check = new Check("name");
$check->addValidator(
    new PresenceOf(
        [
            "message" => "Please select one checkbox",
        ]
    )
);


865

This example is just for one checkbox, but I have some of them

Hi @eugen80 Phalcon is awesome but sometimes dont have all you need built and ready to use

You can make your own validator

To-Do check this resources

Good luck and welcome to Phalcon ;)

edited Apr '17

Custom validation:

class MyValidation extends Valiadation
{
    public function initialize()
    {
        $this->add(['checkbox1', 'checkbox2', 'checkbox3', ...], new PresenceOf());
    }
}
class MyForm extends Form
{
    public function getValidation()
    {
        return new MyValidation();
    }

    public function initialize()
    {
        $this->add(new Check("checkbox1"));
        $this->add(new Check("checkbox2"));
        $this->add(new Check("checkbox3"));
    }
}
edited Apr '17

Pay attention if your form needs to persist checkbox (un)checked state, i.e. when there is validation error.

//Controller
$partners_offers_unchecked = $this->request->isPost() && !$this->request->get('partners_offers') ? true : false;
$form = new SignUpForm(null, ['partners_offers_unchecked' => $partners_offers_unchecked]);

//Form definition
 $partnersOffers = new Check('partners_offers');
        if (!$options['partners_offers_unchecked']) {
            $partnersOffers->setDefault('checked');
        }
        $this->add($partnersOffers);