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

CompareValidator处理字符串时用'=='运算符有待商榷 #8884

Closed
hustnaive opened this issue Jun 24, 2015 · 5 comments
Closed

CompareValidator处理字符串时用'=='运算符有待商榷 #8884

hustnaive opened this issue Jun 24, 2015 · 5 comments
Assignees

Comments

@hustnaive
Copy link
Contributor

YiiChina论坛有一个问题:http://www.yiichina.com/question/644
针对规则:array('pwd2', 'compare', 'compareAttribute' => 'password', 'message' => '两次密码必须一致'),输入'00'和'000'时,返回真,验证通过。

而这个时候,我们的期望是字符串'00'和'000'不等。

看了下CompareValidator的实现,发现对字符串的比较是用的'==',而'00' == '000'为真。同样针对'001'和'01'的处理也存在问题。

写了一个测试(见:https://github.com/hustnaive/yii2/blob/master/tests/framework/validators/CompareValidatorTest.php)

    public function testZeroStrValidate() {
        $value = '00';
        $val = new CompareValidator(['type'=>'string','compareValue' => $value]);
        $this->assertTrue($val->validate($value));
        $this->assertFalse($val->validate('000'));

        $value = '001';
        $val = new CompareValidator(['type'=>'string','compareValue' => $value]);
        $this->assertTrue($val->validate($value));
        $this->assertFalse($val->validate('01'));
    }

目前的CompareValidator都没有测试通过。

修改CompareValidator::compareValues,当type为string时用strcmp替代'==',修改后的代码见:https://github.com/hustnaive/yii2/blob/master/framework/validators/CompareValidator.php

经过测试修复了上述问题。

看看我的修复方案有无问题?

@hiscaler
Copy link
Contributor

你可以使用 operator 属性,赋值为:===

@hustnaive
Copy link
Contributor Author

@hiscaler 如果'>='场景呢?

@hiscaler
Copy link
Contributor

@hustnaive 你可以看看 CompareValidator 的实现源码,都是可以的。

@hustnaive
Copy link
Contributor Author

@hiscaler '000' >= '00' 和 '00' >= '000'都为真,这个是我们预期的么?就是type=>string的时候,对'000'和'00'的比较,你觉得他们之间没有“大小”?

不知道是不是我表述得有问题,还是你没有理解我提出的问题?

@klimov-paul
Copy link
Member

Closed unless readable description provided.

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

4 participants