Browse Source

优化独立验证器

master
kuangweijian 3 years ago
parent
commit
d53d346296
  1. 25
      examples/my-validator.php
  2. 13
      src/MyValidator.php
  3. 20
      src/UserInput.php

25
examples/my-validator.php

@ -0,0 +1,25 @@
<?php
namespace Wiggins\MyProject\Example;
require __DIR__.'/../vendor/autoload.php';
require __DIR__.'/../vendor/yiisoft/yii2/Yii.php';
use Wiggins\MyProject\UserInput;
use Wiggins\MyProject\MyValidator;
//创造一个模型对象
$model=new UserInput(['scenario'=>'login']);
$inputDate=[
"name" => "kuangweijian",
"password" => "123456546",
];
$model->setAttributes($inputDate);
//使用独立验证器
$validator = new MyValidator();
if($validator->validateAttribute($model, "name")){
echo "login succ".PHP_EOL;
}else{
echo "login failed".PHP_EOL;
print_r($model->getErrors());
}
?>

13
src/MyValidator.php

@ -3,13 +3,22 @@
use yii\validators\Validator;
/**
* MyValidator类用于独立验证器
* @author kuangweijian <867034892@qq.com>
* @since 1.0.0
*/
class MyValidator extends Validator
{
public function validateAttribute($model, $attribute)
{
if(!in_array($model->$attribute,['kuangweijian'])){
$this->addError($model, $attribute,"属性中必须含有值'kuangweijian'");
$blackList="kuangweijian";
if((strcmp($blackList, $model->{$attribute})==0))
{
$this->addError($model, $attribute,"{$blackList}属于黑名单人员");
return false;
}
return true;
}
}
?>

20
src/UserInput.php

@ -69,27 +69,7 @@
['pwdConfirm','compare','compareAttribute'=>'password','message'=>'两次密码必须一致'],
[['name','email','password','pwdConfirm'],'required','on'=>'register'],
[['name','password'],'required','on'=>'login'],
[['name','email'],'Wiggins\MyProject\MyValidator']
];
}
}
/**
* MyValidator类用于独立验证器
* @author kuangweijian <867034892@qq.com>
* @since 1.0.0
*/
class MyValidator extends Validator
{
public function validateAttribute($model, $attribute)
{
$blackList='kuangweijian';
if(in_array($blackList, $model->attributes)) //判断黑名单是否在属性数组中
{
$this->addError($model, $attribute,"{$blackList}属于黑名单人员");
}
}
}
?>
Loading…
Cancel
Save