Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bwrigley's avatar

Validating a required checkbox

I'm sure this is an obvious question but I'm not getting it.

I have a field in a model which is a boolean isValid

I want to represent this on a form as a checkbox.

I also want the field to be required as the DB needs a true of false, so I have set the validator to required.

The problem is that an unchecked checkbox returns no value and so validation fails. Any thoughts on how to get round this?

0 likes
4 replies
Snapey's avatar
Snapey
Best Answer
Level 122

Unfortunately it cannot be required as as you have noted, unchecked means its not present. It also does not make any sense to be required since you know that if it is present then it means true and if it is missing it means false.

No need/point in validating in my book.

1 like
tykus's avatar

No need/point in validating in my book.

This. It can have two states - either it is on (and present) or not.

bwrigley's avatar

Yes of course, that's a very valid point. More coffee needed! Thanks.

Kriptic's avatar

so you have the column as a boolean in db? I know when I had to deal with a similar issue, I had to write a function that did this:

public function integerCheckBoxes($request)
{
    $request->checkbox = $request->checkbox ? $request->checkbox : 0;
    return $request
}

or in your case

public function booleanCheckBoxes($request)
{
    $request->checkbox = $request->checkbox ? $request->checkbox : false;
    return $request
}

All this does is see if checkbox=1, otherwise, converts , well null into false then returns the request to the calling function

You could put this in your controller, then call it like this


public function someControllerMethod($request)
{
   $request = $this->booleanCheckBoxes($request)

    // your code to put it in db here
}

it all depends on how you setup your column in the DB, I made mine an integer

Please or to participate in this conversation.