Yii2中Model验证失败返回JSON的核心是先调用validate()捕获错误,再统一返回含errors字段的结构化JSON响应。示例包含UserForm模型定义、SiteController中actionSignup处理逻辑、前端fetch调用方式及注意事项。

<p>Yii2 中 Model 验证失败时返回 JSON,核心是捕获验证错误并统一输出结构化响应。下面是一个完整、可直接使用的示例(含控制器动作 + Model 定义)。</p>
<H3>1. 定义一个带验证规则的 Model</H3>
<p>比如 <strong>UserForm.php</strong>(放在 <code>models/</code> 目录下):</p>
<font color="#666">
<pre class="brush:php;toolbar:false;">
<?php
namespace app\models;
use yii\base\Model;
class UserForm extends Model
{
public $name;
public $email;
public $age;
public function rules()
{
return [
[['name', 'email'], 'required'],
['email', 'email'],
['age', 'integer', 'min' => 1, 'max' => 120],
];
}
public function attributeLabels()
{
return [
'name' => '姓名',
'email' => '邮箱',
'age' => '年龄',
];
}
}
2. 在 Controller 中处理提交并返回 JSON
比如在 SiteController.php 中添加 action:
public function actionSignup()
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$model = new UserForm();
$model->load(\Yii::$app->request->post(), '');
if ($model->validate()) {
// 验证通过:执行业务逻辑(如保存用户)
// return ['success' => true, 'message' => '注册成功'];
return ['success' => true];
} else {
// 验证失败:返回错误详情
return [
'success' => false,
'errors' => $model->getErrors(), // 格式:['email' => ['邮箱格式不正确']]
];
}
}
3. 前端调用示例(fetch)
确保请求是 POST,Content-Type 为 application/x-www-form-urlencoded 或 application/json:
fetch('/site/signup', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
'UserForm[name]': '张三',
'UserForm[email]': 'invalid-email',
'UserForm[age]': '200'
})
})
.then(res => res.json())
.then(data => {
if (data.success) {
console.log('成功');
} else {
console.log('错误:', data.errors);
// 输出示例:{ email: ["邮箱格式不正确"], age: ["年龄必须在 1 和 120 之间。"] }
}
});
4. 可选:全局统一 JSON 错误响应(进阶)
若项目大量接口需一致行为,可在 config/web.php 中配置 beforeAction 或使用自定义行为。但对单个接口,上面方式已足够清晰可靠。
注意:不要在 validate() 前调用 save(),否则会跳过验证直接报数据库错误;务必先 validate,再决定是否入库。


















