Yii2,自定义验证:clientValidateAttribute()无法正常工作

时间:2015-09-11 21:51:17

标签: php yii2 yii2-validation

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

$company_profile_data->postal_code = $_POST['CompanyProfiles']['postal_code'];
$company_profile_data->update();

我决定使用独立验证器进行邮政编码验证。 模型中此属性的规则

public function rules() {
    return [
        //...some other rules...
        ['postal_code', 'string', 'length' => [6,6]],
        ['postal_code', PostalValidator::className()], //standalone validator
    ];
}

app / components / validators / PostalValidator类代码

namespace app\components\validators;

use yii\validators\Validator;
use app\models\CompanyProfiles;
use app\models\Users;

class PostalValidator extends Validator {
    public function init() {
        parent::init();
    }

    public function validateAttribute($model, $attribute) {

    if (!preg_match('/^[0-9]{2}-[0-9]{3}$/', $model->$attribute))
        $model->addError($attribute, 'Wrong postal code format.');
    }

public function clientValidateAttribute($model, $attribute, $view) { //want js-validation too
    $message = 'Invalid status input.';
    return <<<JS
if (!/^[0-9]{2}-[0-9]{3}$/.test("{$model->$attribute}")) {
    messages.push("$message");
}
JS;
    }
}

因此,正确代码的示例是 00-202

当我(在用户角色中)输入错误的值时,页面重新加载并看到Wrong postal code format.消息,虽然我重新定义了clientValidateAttribute方法并写了JS-validation,正如我所建议的那样,不允许页面重新加载。然后我再次按下提交按钮:这个时间页面没有重新加载,我看到Invalid status input.消息(所以,第二次按下时间JS触发)。但是当我输入正确的代码之后,我仍然会看到Invalid status input.消息并且没有任何反应。

那么,我的clientValidateAttribute()方法出了什么问题? validateAttribute()效果很好。

更新 来自控制器的代码段

public function actionProfile(){ //can't use massive assignment here, cause info from 2 (not 1) user models is needed
    if (\Yii::$app->user->isGuest) {
        return $this->redirect('/site/index/');
    }
    $is_user_admin = Users::findOne(['is_admin' => 1]);
    if ($is_user_admin->id == \Yii::$app->user->id)
        return $this->redirect('/admin/login/');

    $is_user_blocked = Users::find()->where(['is_blocked' => 1, 'id' => \Yii::$app->user->id])->one();
    if($is_user_blocked)
        return $this->actionLogout();

//3 model instances to retrieve data from users && company_profiles && logo
    $user_data = Users::find()->where(['id'=>\Yii::$app->user->id])->one();
    $user_data->scenario = 'update';

    $company_profile_data = CompanyProfiles::find()->where(['user_id'=>Yii::$app->user->id])->one();
    $logo = LogoData::findOne(['user_id' => \Yii::$app->user->id]);
    $logo_name = $logo->logo_name; //will be NULL, if user have never uploaded logo. In this case placeholder will be used

    $upload_logo = new UploadLogo();
    if (Yii::$app->request->isPost) {

        $upload_logo->imageFile = UploadedFile::getInstance($upload_logo, 'imageFile');

        if ($upload_logo->imageFile) { //1st part ($logo_data->imageFile) - whether user have uploaded logo
            $logo_file_name = md5($user_data->id);
            $is_uploaded = $upload_logo->upload($logo_file_name);
            if ($is_uploaded) { //this cond is needed, cause validation for image fails (?)
                //create record in 'logo_data' tbl, deleting previous
                if ($logo_name) {
                    $logo->delete();
                } else { //if upload logo first time, set val to $logo_name. Otherwise NULL val will pass to 'profile' view, and user wont see his new logo at once
                    $logo_name = $logo_file_name.'.'.$upload_logo->imageFile->extension;
                }
                $logo_data = new LogoData;
                $logo_data->user_id = \Yii::$app->user->id;
                $logo_data->logo_name = $logo_name;
                $logo_data->save();
            }
        }
    }

    if (isset($_POST['CompanyProfiles'])){

        $company_profile_data->firm_data = $_POST['CompanyProfiles']['firm_data'];
        $company_profile_data->company_name = $_POST['CompanyProfiles']['company_name'];
        $company_profile_data->regon = $_POST['CompanyProfiles']['regon'];
        $company_profile_data->pesel = $_POST['CompanyProfiles']['pesel'];
        $company_profile_data->postal_code = $_POST['CompanyProfiles']['postal_code'];
        $company_profile_data->nip = $_POST['CompanyProfiles']['nip'];
        $company_profile_data->country = $_POST['CompanyProfiles']['country'];
        $company_profile_data->city = $_POST['CompanyProfiles']['city'];
        $company_profile_data->address = $_POST['CompanyProfiles']['address'];
        $company_profile_data->telephone_num = $_POST['CompanyProfiles']['telephone_num'];
        $company_profile_data->email = $_POST['CompanyProfiles']['email'];          
        $company_profile_data->update();
    }

    if (isset($_POST['personal-data-button'])) {
        $user_data->username = $_POST['Users']['username'];
        $user_data->password_repeat = $user_data->password = md5($_POST['Users']['password']);
        $user_data->update();
    }
    return $this->render('profile', ['user_data' => $user_data, 'company_profile_data' => $company_profile_data, 'upload_logo' => $upload_logo, 'logo_name' => $logo_name]);
}

2 个答案:

答案 0 :(得分:2)

我的不准确性是clientValidateAttribute()方法。而不是代码段中的$model->$attribute

if (!/^[0-9]{2}-[0-9]{3}$/.test("{$model->$attribute}")) {

...我不得不使用预定义的JS-var value,导致此变化随输入值的变化而变化。所以,我的新代码是:

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

答案 1 :(得分:0)

模型在模型中not called any function之前不会加载规则和行为。当您拨打$company_profile_data->update();模型通话updatevalidate功能时。

尝试在$company_profile_data = CompanyProfiles::find()此代码之后添加:

$company_profile_data->validate();

或者只使用load功能。我认为这会有所帮助。