Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Form validation for fields of type "number" fails sometimes even if the value is valid. #3761

Closed
hurlon opened this issue Oct 25, 2023 · 0 comments

Comments

@hurlon
Copy link

hurlon commented Oct 25, 2023

My form validation fails sometimes for fields of type number with float values and using decimal steps, even if the float value is valid.

Blueprint example used in the form:

myfield:
  type: number
  label: "Level between -10 and 10 with 1 digit after the decimal point"
  placeholder: '-1.5'
  validate:
    min: -10.0
    max: 10.0
    step: 0.1

Sometimes the validation is ok and sometimes it fails (for example, a value of -1.9 does not pass the valiation while a value of -1.8 is valid)

This issue seems to be a wrong float to int conversion due to floating point error in the validation function.

My suggestion to overcome this probleme is to 'round' the float before testing. Following code modification of the data Validation class is working for me:

--- Validation.php     2023-07-18 18:43:00.000000000 +0200
+++ Validation.php      2023-10-25 09:01:16.758049200 +0200
@@ -550,7 +550,9 @@
             $step = (float)$params['step'];
             // Count of how many steps we are above/below the minimum value.
             $pos = ($value - $min) / $step;
+            // prevent wrong validation due to floating point precision
+            $pos = round($pos, 4);

             return is_int(static::filterNumber($pos, $params, $field));
         }

If my understanding of the function is right, $pos should be an integer if we want a positiv validation, so the rounding with 1 or more digit after the decimal point should be ok. I choose a rounding with 4 decimal thinking I will be on the safe side.

Tests were done with Grav v1.7.43, which is the last official release as of this writing, on Linux/Apache and on Xammp for Windows with the same issues

PS: I'm not an advanced PHP developper by far and I can't guarantee that this is the best solution, but it works for me on my specific project.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant