Yii Ad Hoc验证
有时您需要验证未绑定到任何模型的值。您可以使用 yii \ base \ DynamicModel 类,它支持即时定义属性和规则。
第1步 - 将 actionAdHocValidation 方法添加到 SiteController 。
public function actionAdHocValidation() {
$model = DynamicModel::validateData([
'username' => 'John',
'email' => 'john@gmail.com'
], [
[['username', 'email'], 'string', 'max' => 12],
['email', 'email'],
]);
if ($model->hasErrors()) {
var_dump($model->errors);
} else {
echo "success";
}
}
在上面的代码中,我们定义了一个包含用户名和电子邮件属性的 “动态” 模型并验证它们。
第2步 - 在Web浏览器的地址栏中键入 http:// localhost:8080 / index.php?r =站点/特别验证 ,您将看到一条错误消息,因为我们的电子邮件长度为14个字符。

自定义验证器
有两种类型的自定义验证程序 -
- 内联验证器
- 独立验证器
内联验证器由模型方法或匿名函数定义。如果某个属性未通过验证,则应调用 yii \ base \ Model :: addError() 方法来保存错误消息。
以下 RegistrationForm 示例验证city属性,因此它只能接受两个值 - 伦敦和巴黎。
<?php
namespace app\models;
use Yii;
use yii\base\Model;
class RegistrationForm extends Model {
public $username;
public $password;
public $email;
public $country;
public $city;
public $phone;
public function rules() {
return [
['city', 'validateCity']
];
}
public function validateCity($attribute, $params) {
if (!in_array($this->$attribute, ['Paris', 'London'])) {
$this->addError($attribute, 'The city must be either "London" or "Paris".');
}
}
}
?>
独立的验证器扩展了 yii \ validators \ Validator 类。要实现验证逻辑,您应该重写 yii \ validators \ Validator :: validateAttribute() 方法。
第1步 - 要使用独立验证程序实现前面的示例,请将 CityValidator.php 文件添加到 组件 文件夹。
<?php
namespace app\components;
use yii\validators\Validator;
class CityValidator extends Validator {
public function validateAttribute($model, $attribute) {
if (!in_array($model->$attribute, ['Paris', 'London'])) {
$this->addError($model, $attribute, 'The city must be either "Paris"
or "London".');
}
}
}
?>
第2步 - 然后,以 这种方式修改 RegistrationForm 模型。
<?php
namespace app\models;
use app\components\CityValidator;
use Yii;
use yii\base\Model;
class RegistrationForm extends Model {
public $username;
public $password;
public $email;
public $country;
public $city;
public $phone;
public function rules() {
return [
['city', CityValidator::className()]
];
}
}
?>
下一章:Yii AJAX验证
用户名验证只能在服务器端进行,因为只有服务器具有所需的信息。在这种情况下,您可以使用基于AJAX的验证。第1步 - 要启用AJAX验证,请按照 这种方式修改 注册 视图。<?php use yii\bootstr ...
AI 中文社