Currently, the numeric validation uses $this->value != '' to determine if the field has a value. However, PHP will convert '' to 0 when comparing against a numeric value. As a result, if $this->value is set to 0 then the condition will fail. I want a validation for a commerce price field to ensure that the value is greater than zero (I'm using 0.01 for the minimum) but it passes when zero is used. A simple solution would be to use strlen($this->value) to check for a value.

Comments

BassistJimmyJam’s picture

Status: Active » Needs review
StatusFileSize
new783 bytes

Patch attached.

g089h515r806’s picture

Do you mean that you set 0.01 as the minimum value, but 0 is still could pass the validation?

BassistJimmyJam’s picture

That is correct. Since 0 was considered an empty value, the validation would not actually run and would therefore pass.

g089h515r806’s picture

I have test it on my local site, add a test field,
add numeric validator to it, set minimum value = 3,

I enter 0 to test it, i get the error message. It works.

The value that post by a form is always a string. If you enter 0,
the actually value of "$this->value" is '0', not 0.

maybe you have converted '0' to 0 before validation.

g089h515r806’s picture

I have read the code of commerce, and find that it convert the price from string to numeric in its validate function which is called before field validation.

Maybe we could change the code to:

$this->value !== ''

It is more meaning full than using strlen at here.

BassistJimmyJam’s picture

StatusFileSize
new808 bytes

That doesn't handle NULL values. While form submit should not include NULL values, a field type may change empty values similar to how commerce price converted the value to an integer. $this->value !== '' && !is_null($this->value) should handle that and I have updated my patch accordingly and verified that it still works as expected.

g089h515r806’s picture

patch commited.
Other validators still use :

$this->value != ''

Maybe we could change them later.

It is not a good idea to change the value of user input in validate function, however commece is a popular module, we need make this module compatable with it.

g089h515r806’s picture

Status: Needs review » Fixed

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.