Custom validation before submitting form

I have looked all over the web and just can’t figure out what do I have to do in my situation.
I have a form, where you can upload a file with many items or upload a single item by using a string.
This is my custom validation for this

    public function validateAttribute($model, $attribute)
    {
        if (empty($this->file) && empty($this->value)) {
            $this->addError($model, $attribute, \Yii::t('app', 'One field must be filled'));
            return false;
        }
        if (!empty($this->file) && !empty($this->value)) {
            $this->addError($model, $attribute, \Yii::t('app', 'Only one field can be filled at a time'));
            return false;
        }
        return true;
    }

Now the part I just can’t figure out is how can I make this validation work before user presses the submit button.

I read the docs and understand that the logic has to be in this method and the validation above is in a seperate file made specifically for this validator

    public function clientValidateAttribute($model, $attribute, $view)
    {

    }

Can anyone help me understand what do I have to write here, because I’m not sure I fully understand the idea behind this.
I have to make sure that the user can fill out either of the fields, but not both at the same time or leave them both empty.

Hi, @mrzalais !
The idea behind the clientValidateAttribute is to help you with your client-side validation (the browser side).

I’ll give you an example how I made so you can start to plan your solution.

public function clientValidateAttribute($model, $attribute, $view)
{
    $message = json_encode($this->message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); 

    return <<<JS
        possible = $('#credits-amount').data().customerCredit;
        if ( value > possible ) {
            messages.push($message);
        }
        JS;
}

So basically this code triggers an error on the form before before submitting (validate). It’s actually pretty simple.

I hope my answer will point you some good direction, I’m kinda in a rush here and couldn’t explain more. But let me know if this already help you, otherwise I can comeback later and try to give you more insights.

Have a nice week!