Search code examples
phpvalidationyii2-advanced-appactive-form

Custom Field Validator Client Side on Yii2


I have some trouble when i try to add a custom Validator rule for my input. This is my code.

MODEL

class Category extends \yii\db\ActiveRecord{

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'cat';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['cat_cod','cat_deep','cat_father'], 'required'],
            //other rules
            [['cat_cod'], 'test'],

        ];
    }
    public function test($attribute){
        $cat_cod = $this->$attribute;
        if($cat_cod == 'test'){
            $this->addError($attribute,"Error Test");
        }
    }

So, this is only a test, but it works fine when i submit my form, but it doesn't work in client side validaton.

if cat_cod is empty:

cat_cod is empty

if i write test in the input field

enter image description here

In the 2 image when i write test doesn't validate on client side

UPDATE Afte Yupik Comment, server side validation works fine, so if i want to add client side validation i must implement an AjaxValidation. So i've activated ajax validation in only one field like this

$form->field($model, 'cat_cod',['enableAjaxValidation' => true])->textInput();

Now in my controller how can i handle this? Documentation is not very clear. This is What i've try

if($model->load(Yii::$app->request->post()) && $model->validate()){
        if (Yii::$app->request->isAjax ) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
   //something else

Solution

  • Because this is server side validator. To add client side validator use whenClient to check whether rule should be applied. Read more docs