Since you didn't post enough code for anyone to tell what you have, this is as close as I can get. I may update this answer if you add more code. We need to see more of your model, controller, and view.
In the view file, it would help so I can see what ID's are being assigned to your inputs, which would allow me to provide more detailed code. So for right now, you need to look at your form and look at the ID's on the input elements. Replace REPLACEHERE in the javascript below with whatever your ID's start with.
model
['state_name', 'required', 'when' => function($model) {
return !empty($model->country_name);
}, 'whenClient' => "isCountryEmpty"
],
place at the bottom of your view file:
<?php $this->registerJs('
function isCountryEmpty (attribute, value) {
return ($("#REPLACEHERE-country_name").val().length > 0) ? true : false;
};
jQuery( "#REPLACEHERE-country_name" ).keyup(function() {
$("#w0").yiiActiveForm("validateAttribute", "REPLACEHERE-state_name");
$("#w0").yiiActiveForm("validateAttribute", "REPLACEHERE-country_name");
});
jQuery( "#REPLACEHERE-state_name" ).keyup(function() {
$("#w0").yiiActiveForm("validateAttribute", "REPLACEHERE-state_name");
$("#w0").yiiActiveForm("validateAttribute", "REPLACEHERE-country_name");
});
'); ?>
The whenClient in the model tells it to run client validation and calls the isStateEmpty function in the javascript. The other 2 javascripts detect changes on the state and country inputs. On keyup they trigger the Yii ActiveForm javascript to re-validate.
Hope that helps you out!
Edit
After you added your view's code, your names are incorrect. In your view, you have state_name and country_name but in your model you used only state. I have updated my code above to reflect that.
If your not using the Yii form, you will not get client validations. Those are bound by specialized Yii ID's attached to the elements when ActiveForm creates your form.
$model = Country::findOne($country_id); $model->load(Yii::$app->request->post());var_dump(Yii::$app->request->post())?stateis only required when country is not null. 2, I am not sure ifenableClientValidationworks on the rules? It goes on yourActiveFormwidget in your view. If you need to toggle it, use jQuery and toggle it based on a field on your form. 3, those rules you defined don't trigger until you run$model->validate()... We need to see more of your code. The view, controller, and models related.