自定义验证在 yii2 中不起作用
custom validation not work in yii2
我用过自定义 validation.But 它不起作用。
这是我的模型
class Manufacture extends \yii\db\ActiveRecord
{
public function rules()
{
return [
[['model_no'], 'safe'],
['model_no', 'customValidation', 'skipOnEmpty' => false, 'skipOnError' => false],
];
}
public function customValidation($attribute, $params)
{
if($this->model_no=='test')
{
$this->addError($attribute,'add proper data.');
}
}
}
在控制器中
public function actionCreate()
{
if ($model->load(Yii::$app->request->post())) {
if ($model->validate()) {
//some code
}
}
}
这里我在安全中添加了属性,但我的错误仍然没有显示在视图表单中。
// MODLE CODE
class Manufacture extends \yii\db\ActiveRecord
{
public function rules()
{
return [
[['model_no'], 'required'],
['model_no', function ($attribute, $params)
{
if ($this->$attribute == 'test')
{
$this->addError($attribute, 'You have entered test');
}
else
{
$this->addError($attribute, "You have not entered test but you have entered {$this->$attribute} ");
}
}],
];
}
}
// CONTROLLER CODE
public function actionCreate()
{
$model = new Manufacture();
if ($model->load(Yii::$app->request->post()))
{
if ($model->validate())
{
//HERE YOU CAN WRITE YOUR CODE TO SAVE THE DATA
}
else
{
// HERE YOU CAN PRINT THE ERRORS OF MODEL
echo "<pre>";
print_r($model->getErrors());
echo "</pre>";
}
}
}
我用过自定义 validation.But 它不起作用。 这是我的模型
class Manufacture extends \yii\db\ActiveRecord
{
public function rules()
{
return [
[['model_no'], 'safe'],
['model_no', 'customValidation', 'skipOnEmpty' => false, 'skipOnError' => false],
];
}
public function customValidation($attribute, $params)
{
if($this->model_no=='test')
{
$this->addError($attribute,'add proper data.');
}
}
}
在控制器中
public function actionCreate()
{
if ($model->load(Yii::$app->request->post())) {
if ($model->validate()) {
//some code
}
}
}
这里我在安全中添加了属性,但我的错误仍然没有显示在视图表单中。
// MODLE CODE
class Manufacture extends \yii\db\ActiveRecord
{
public function rules()
{
return [
[['model_no'], 'required'],
['model_no', function ($attribute, $params)
{
if ($this->$attribute == 'test')
{
$this->addError($attribute, 'You have entered test');
}
else
{
$this->addError($attribute, "You have not entered test but you have entered {$this->$attribute} ");
}
}],
];
}
}
// CONTROLLER CODE
public function actionCreate()
{
$model = new Manufacture();
if ($model->load(Yii::$app->request->post()))
{
if ($model->validate())
{
//HERE YOU CAN WRITE YOUR CODE TO SAVE THE DATA
}
else
{
// HERE YOU CAN PRINT THE ERRORS OF MODEL
echo "<pre>";
print_r($model->getErrors());
echo "</pre>";
}
}
}