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.
| Comment | File | Size | Author |
|---|---|---|---|
| #6 | strlen-for-numeric-1663098-6.patch | 808 bytes | BassistJimmyJam |
| #1 | strlen-for-numeric-1663098-1.patch | 783 bytes | BassistJimmyJam |
Comments
Comment #1
BassistJimmyJam commentedPatch attached.
Comment #2
g089h515r806 commentedDo you mean that you set 0.01 as the minimum value, but 0 is still could pass the validation?
Comment #3
BassistJimmyJam commentedThat is correct. Since 0 was considered an empty value, the validation would not actually run and would therefore pass.
Comment #4
g089h515r806 commentedI 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.
Comment #5
g089h515r806 commentedI 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:
It is more meaning full than using strlen at here.
Comment #6
BassistJimmyJam commentedThat doesn't handle
NULLvalues. While form submit should not includeNULLvalues, 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.Comment #7
g089h515r806 commentedpatch commited.
Other validators still use :
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.
Comment #8
g089h515r806 commented