Php Yii2,自定义验证:clientValidateAttribute()不';我不能正常工作

Php Yii2,自定义验证:clientValidateAttribute()不';我不能正常工作,php,yii2,yii2-validation,Php,Yii2,Yii2 Validation,我有一个表单,由ActiveForm小部件创建。用户在那里输入波兰邮政编码。在适当的控制器中,我将输入的数据放入数据库中,例如: $company_profile_data->postal_code = $_POST['CompanyProfiles']['postal_code']; $company_profile_data->update(); 我决定使用独立验证器进行邮政编码验证。模型中此属性的规则: 应用程序/组件/验证程序/PostalValidator类别代码: 只有

我有一个表单,由ActiveForm小部件创建。用户在那里输入波兰邮政编码。在适当的控制器中,我将输入的数据放入数据库中,例如:

$company_profile_data->postal_code = $_POST['CompanyProfiles']['postal_code'];
$company_profile_data->update();
我决定使用独立验证器进行邮政编码验证。模型中此属性的规则:

应用程序/组件/验证程序/PostalValidator类别代码:


只有从模型中加载规则和行为,模型才会加载规则和行为。当您调用
$company\u profile\u data->update()时模型调用
更新
验证
功能

$company\u profile\u data=CompanyProfiles::find()之后尝试添加此代码:

$company_profile_data->validate();

或者只需使用
load
功能。我想这会有帮助。

我的错误在于
clientValidateAttribute()
方法。代替代码段中的
$model->$attribute

if (!/^[0-9]{2}-[0-9]{3}$/.test("{$model->$attribute}")) {
…我必须使用预定义的JS变量,因为此变量随输入值的变化而变化。因此,我的新代码是:

public function clientValidateAttribute($model, $attribute, $view) {
    return <<<JS
if (!/^[0-9]{2}-[0-9]{3}$/.test(value)) {
    messages.push("Wrong postal code format.");
} 
JS;
}
公共函数clientValidateAttribute($model、$attribute、$view){

return您正在使用load函数?我想load只在提交表单之后调用。不,我不使用它。我这样做(正如我上面所写的):
$company\u profile\u data->postal\u code=$\u POST['CompanyProfiles']['postail\u code']
。因此,我不使用大规模赋值。您知道,其他属性正确验证(提交之前)没有任何
load()
。但不是在独立验证的情况下。我发现控制器有问题。你可以用控制代码更新帖子?当然。以防万一我添加了所有
actionProfile
代码,但是,我想,最有趣的部分是
IF
stmt:
IF(isset($\u post['CompanyProfiles')){…
。两种情况都没有成功。但是,我想,我已经解决了这个问题。感谢您的参与。:)
$company_profile_data->validate();
if (!/^[0-9]{2}-[0-9]{3}$/.test("{$model->$attribute}")) {
public function clientValidateAttribute($model, $attribute, $view) {
    return <<<JS
if (!/^[0-9]{2}-[0-9]{3}$/.test(value)) {
    messages.push("Wrong postal code format.");
} 
JS;
}