簡體   English   中英

Yii2,自定義驗證:clientValidateAttribute()無法正常工作

[英]Yii2, custom validation: clientValidateAttribute() doesn't work correctly

我有一個由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()效果很好。

來自控制器的 UPDATE Snippet

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]);
}

我的不准確之處在於clientValidateAttribute()方法。 而不是$model->$attribute code in code snippet:

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

...我必須使用預定義的JS-var ,導致此變化隨輸入值的變化而變化。 所以,我的新代碼是:

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

在沒有從模型中調用任何函數之前 ,模型不會加載規則和行為。 當你調用$company_profile_data->update(); 模型調用updatevalidate功能。

嘗試在$company_profile_data = CompanyProfiles::find()之后添加此代碼:

$company_profile_data->validate();

或者只使用load功能。 我認為這會有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM