Yii2:独立验证不触发客户端验证



验证函数不起作用。 验证海关规则不适用于usernmane字段

module dektrium/user
PHP 7.1
Yii 2.0.16

已经从这里尝试了所有内容:https://www.yiiframework.com/doc/guide/2.0/en/input-validation(内联验证器和独立验证器)

模型代理:

class Agent extends Profile
{
public $username;
public $password;
public $password2;
public function rules()
{
$rules = [
['username', AgentValidator::className()],// it's not work
[['email'], 'email'], // it's work
['password2', 'compare', 'compareAttribute' => 'password', 'message' => 'Пароли должны совпадать'],//// it's work
];
return array_merge(parent::rules(), $rules);
}
}

代理验证器.php

<?php
namespace appcomponents;
use yiivalidatorsValidator;
class AgentValidator extends  Validator
{
public function validateAttribute($model, $attribute)
{
if (User::findOne(['username' => $this->$attribute]]) {
$this->addError($attribute, 'Такой логин уже занят');
}
}
}

您正在使用独立验证器,并且希望前端验证与后端一起工作,因此您需要覆盖独立验证器AgentValidator中的yiivalidatorsValidator::clientValidateAttribute(),这将返回一段在客户端执行验证的 JavaScript 代码。

在 JavaScript 代码中,您可以使用以下预定义变量:

  • attribute:正在验证的属性的名称。
  • value:正在验证的值。
  • messages:用于保存属性的验证错误消息的数组。
  • deferred:可以将延迟对象推入的数组。

可以阅读实现客户端验证部分以详细阅读。

除了上面列出的所有内容之外,您的验证器代码User::findOne(['username' => $this->$attribute]]中还有一个错误,您需要使用$model->$attribute而不是$this->$attribute,它永远不会获得在表单中输入的确切值。您可能错误地从模型中添加了它。

您当前的验证器应如下所示

<?php
namespace appcomponents;
use yiivalidatorsValidator;
class AgentValidator extends  Validator
{
public $message='Такой логин уже занят';
public function validateAttribute($model, $attribute)
{
if (User::findOne(['username' => $model->$attribute])!==null) 
{
$model->addError($attribute, $this->message);
}
}
public function clientValidateAttribute($model, $attribute, $view) {
//check if user exists
$userExists = User::findOne(['username' => $model->$attribute])!==null;
$message = json_encode($this->message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
return <<<JS
if($userExists){
messages.push($message);
return;
}
JS;
}
}

所以,感谢穆罕默德·奥马尔·阿斯拉姆的正确答案。 Yii2 不会生成任何 js 代码来通过自定义规则进行验证。因此,有必要在控制器和表单中添加检查 对我来说: 控制器

if (Yii::$app->request->isAjax) {
Yii::$app->response->format = yiiwebResponse::FORMAT_JSON;
$model->load(Yii::$app->request->post());
return yiiwidgetsActiveForm::validate($model);
}

形式

$form = ActiveForm::begin([ 'enableAjaxValidation' => true]); 

最新更新