I want to make custom validation function like built-in validation required. I have example code here:
Model:
use yii\base\Model;
class TestForm extends Model
{
public $age;
public function rules(){
return [
['age', 'my_validation']
];
}
public function my_validation(){
//some code here
}
}
View:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
$this->title = 'test';
?>
<div style="margin-top: 30px;">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'age')->label("age") ?>
<div class="form-group">
<?= Html::submitButton('submit', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Controller:
use app\models\form\TestForm;
use yii\web\Controller;
class TestController extends Controller
{
public function actionIndex(){
$model = new TestForm();
if($model->load(\Yii::$app->request->post())){
return $this->render('test', array(
'model'=>$model,
'message'=>'success'
));
}
return $this->render('test', array('model'=>$model));
}
}
in this example I have a field for age and this my_validation function should check if age is over 18 before submit and throw error if age is under 18. This validation should be processed by ajax like it is in case of required rule if you try to submit empty field.
Although you can use
Conditional ValidatorswhenandwhenClienttoo in your scenario but I would recommend using a more sophisticated way which is to define a custom validator because according to the docsSo what you need to do is create a validator and add it to your rules against the field you want.
You need to be careful copying the following code IF you haven't provided the actual model name and update the field names accordingly.
1) First thing to do is to update the
ActiveFormwidget to the following2) Change your model
rules()function to the following3) Remove the custom validation function
my_validation()from your model i hope you are checking the age limit in it to be18+we will move that logic into the validator.Now create a file
AgeValidator.phpinsidecomponentsdirectory, if you are using thebasic-appadd the foldercomponentsinside the root directory of the project if it does not exist create a new one, and copy the following code inside.BUT
I have assumed the name of the Model that is provided by you above so if it not the actual name you have to update the field name inside the
javascriptstatements withinclientValidateAttributefunction you see below in the validator because theidattribute of the fields inActiveFormis generated in a format like#modelname-fieldname(all small case) so according to above given model, it will be#testform-agedo update it accordingly otherwise the validation wont work. And do update the namespace in the validator below and in the modelrules()if you plan to save it somewhere else.