Skip to content

Instantly share code, notes, and snippets.

@ericduran
Created June 10, 2011 05:49
Show Gist options
  • Save ericduran/1018300 to your computer and use it in GitHub Desktop.
Save ericduran/1018300 to your computer and use it in GitHub Desktop.
Validate the html5 step attribute in PHP
<?php
/**
* php port from C++
* All the logic taken from the chrome/webkit/idk team ;)
* http://codesearch.google.com/#OAMlx_jo-ck/src/third_party/WebKit/Source/WebCore/html/NumberInputType.cpp&type=cs&l=129&q=acceptableError&exact_package=chromium
*/
define ("DBL_MANT_DIG", 16);
define ("FLT_MANT_DIG", 16);
/**
* returns TRUE is there is a mis match
*/
function stepMismatch($value, $step) {
(double) $doubleValue;
if (!$doubleValue = (double) $value) {
return false;
}
$doubleValue = abs($doubleValue - 0.0);
if (is_infinite($doubleValue)) {
return false;
}
// double's fractional part size is DBL_MAN_DIG-bit. If the current value
// is greater than step*2^DBL_MANT_DIG, the following computation for
// remainder makes no sense.
if ($doubleValue / pow(2.0, DBL_MANT_DIG) > $step) {
return false;
}
// The computation follows HTML5 4.10.7.2.10 `The step attribute' :
// ... that number subtracted from the step base is not an integral multiple
// of the allowed value step, the element is suffering from a step mismatch.
(double) $remainder = abs($doubleValue - $step * round($doubleValue / $step));
// Accepts erros in lower fractional part which IEEE 754 single-precision
// can't represent.
(double) $computedAcceptableError = acceptableError($step);
return $computedAcceptableError < $remainder && $remainder < ($step - $computedAcceptableError);
}
function acceptableError($step) {
return $step / pow(2.0, FLT_MANT_DIG);
}
$value = 1.2;
$step = 0.4;
if (stepMismatch($value, $step)) {
print "INVALID";
}
else {
print "VALID"; // VALID is Printed
}
$value = 1.2;
$step = 0.5;
if (stepMismatch($value, $step)) {
print "INVALID"; // INVALID Is Printer
}
else {
print "VALID";
}
@ericduran
Copy link
Author

there some useless stuff in here, but is way to late for me to fix that now.

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