0

我有一个表单,用户可以在其中输入浮点值。我将这些值发布到 php 脚本中,并比较用户输入的数字是否介于某些值之间。如果我发布一个整数,无论​​数字是否超出边界,比较都会返回 true。如果我输入一个浮点数,无论该数字是否在边界内,比较都会失败。我并不愚蠢,我已经在 c++ 中进行过浮点比较,并且我知道如何执行 if(float1 >= float2) return false...

这是我的代码:

//loading the helper
$val = Loader::helper('synerciel_form','synerciel_client');
//adding the fields to the inputs array for validation
$val->between('isolation_des_murs_peripheriques', 2.8, null, t($between.'Isolation des murs 
pèriphèriques'), true, false);

//帮助类

class SynercielFormHelper extends ValidationFormHelper {
    const VALID_BETWEEN = 7;
    const VALID_FLOAT = 7;
    private $min;
    private $max;
    private $includeLow;
    private $includeHigh;

 public function between($field, $min, $max, $errorMsg, $includeLow = true, $includeHigh = true) {
        $const = SynercielFormHelper::VALID_BETWEEN;
        $this->min = $min;
        $this->max = $max;
        $this->includeLow = $includeLow;
        $this->includeHigh = $includeHigh;

        $this->addRequired($field, $errorMsg, $const);
    }
   ...
   public function test() {

    $between = new ValidationNumbersBetweenHelper();
    if (!$between->between($this->data[$field], $this->min, $this->max, $this->includeLow, $this->includeHigh)) {
                        $this->fieldsInvalid[] = $f;
}

}

我的验证方法(我相信这是棘手的部分)

class ValidationNumbersBetweenHelper {

    public function between($data, $min = null, $max = null, $includeLow = true, $includeHigh = true) {

        if ($min && $includeLow) {
            if (!($data >= $min))
                return false;
        } else if ($min) {
            if (!($data > $min))
                return false;
        }
        if ($max && $includeHigh) {
            if (!($data <= $max))
                return false;
        } else if ($max) {
            if (!($data < $max))
                return false;
        }
        return true;
    }

}
4

2 回答 2

0

检查警告消息http://php.net/manual/en/language.operators.comparison.php

您可以使用 BC 数学函数http://php.net/manual/en/function.bccomp.php

$status = bccomp($left, $right);
if ($status == 0) {
    echo 'equal';
} else if ($status > 0) {
    echo 'left bigger than right';
} else {
   echo 'right bigger than left';
}

希望这可以帮助

于 2011-06-07T01:54:51.220 回答
0

尝试隔离麻烦的代码。将您的验证函数放入一个独立的 PHP 文件并在那里进行测试。尝试检查$maxand $minfor !== nullas 0is also false。您可以颠倒逻辑并删除所有!s. (例如更改>=<),因此您可以使用“小于”而不是“不大于或等于”

于 2012-07-24T03:30:17.420 回答