我有模型表单(SomeForm
)和自定义验证功能:
use yii\base\Model;
class SomeForm extends Model
{
public $age;
public function custom_validation($attribute, $params){
if($this->age < 18){
$this->addError($attribute, 'Some error Text');
return true;
}
else{
return false;
}
}
public function rules(){
return [
['age', 'custom_validation']
];
}
}
我custom_validation
在rules()
函数中使用它,但表单甚至提交任何具有age
属性的值。
这是表格:
年龄.php
<?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(); ?>
和控制器:
use yii\web\Controller;
class SomeController extends Controller
{
//this controller is just for rendering
public function actionIndex(){
return $this->render('age');
}
public function actionSubmit(){
$model = new SomeForm();
if($model->load(Yii::$app->request->post()){
//do something here
}
}
}