Whats the best boolean field validator?

It's very simple.

The field in the table is a tinyint(1). It stores 0 or 1 (not null in my case).

Looking here: http://www.yiiframew…/api/CValidator

I would like to know which approach is better?

I thought using the match: CRegularExp​ressionValidator with the regular exp​ression: '/^(0|1)$/'

I'd like some opinion.

You can use: array('attribute', 'in', 'range'=>array(0,1))

Well point.

It's easer than "match" method.

Thanks.

My problem is a little bit different :

I have a boolean that must be set, so using boolean validator is fine, but using required validator return error even if I do $obj->attribute=false; (the default value for this attribute is null)

CRequiredValidator doesn’t consider false a value because in isEmpty() that is inherited from CValidator, the following expression is_scalar($value) && trim($value)===’’ is true when $value=false

So the question still remain, how to choose validators for a required boolean ?

Thanks !

Hi jimmy,

please open a new topic for new requests. This topic is 4 years old.

The validators are supposed to validate user form input values. There is no way that the user can submit the native boolean values "true" or "false" to the server. A boolean field takes either the string value "0" (false) or "1" (true). They do also pass the required validator.

Therefore: Instead of $model->attribute = false use $model->attribute = 0 (or $model->attribute = ‘0’)

Thanks for the answer. I will open a new topic next time :rolleyes: