How to validate notEmpty bit value 0/1 #154

Closed
NeedToMeet opened this Issue Mar 5, 2014 · 4 comments

Projects

None yet

5 participants

@NeedToMeet

I noticed that the NotEmpty rule uses PHP's empty(), which always evaluates the value of numeric 0 as false. Values of non-nullable 0 or 1 are common in bit-type fields where an on/off value is set. Any suggestions on how to validate this as non-empty?

@augustohp
Member

I am afraid you are right about the notEmpty rule, which exists to conform with the empty() function.

Although there is no specific rule to do what you want, there a couple of different ways that involve creating a rule composed of more rules:

use Respect\Validation\Validator as v; // as of version 0.5.0

$onOffValidator = v::oneOf(array(
    v::int()->equals(0)->setName('Off'),
    v::int()->equals(1)->setName('On')
))->setName('On/Off');

$onOffValidator = v::int()->in(array(0,1))->setName('On/Off');

$onOffValidator = v::base(2)->length(1,1,true)->setName('On/Off');

Please, let me know if that helps you and if you feel the provided solutions are appropriate for your use cases.

@augustohp augustohp self-assigned this Mar 6, 2014
@flip111 flip111 added a commit to flip111/Validation that referenced this issue May 4, 2014
@flip111 flip111 notEmpty fix
For strings only: notEmpty now means "there was content supplied", rather than "the content was not empty according to the php empty function".

Effect: notEmpty no longer validates to false when string "0" is supplied.

This make more sense when validating HTML forms.

Related issue: Respect#154
19d882c
@flip111 flip111 referenced this issue May 4, 2014
Closed

notEmpty fix #173

0 of 4 tasks complete
@maboiteaspam

@augustohp

Hi,
Is that possible to have a not empty string validator ? Just that, consider value is a string, evaluate it as not empty. That will make things much more simple for everyone and you would keep going with your semantic matter safely, right ?

@dereuromark

You could have a method boolNotEmpty() which would allow 0 and 1 to pass as not empty, whereas "null" or empty string would be empty then. Just an idea.

@henriquemoody
Member

Will be fixed on version 1.0, see changelog for more info about the version.

To fix this issue now all rules are mandatory, but you can use optional() rule to handle optional values, which now is null and an empty string by default.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment