Home >Backend Development >PHP Tutorial >yii2如何自定义模型(model)验证中的错误信息?

yii2如何自定义模型(model)验证中的错误信息?

WBOY
WBOYOriginal
2016-06-06 20:09:461379browse

<code>namespace backend\modules\article\models;
use yii\db\ActiveRecord;

class Category extends ActiveRecord
{
    
    public static function tableName()
    {
        return 'category';
    }
    
    public function rules()
    {
        return [
            [['categoryName','categoryDir'],'required','message'=>'不能为空']
        ];
    }

}</code>

上面定义的错误信息,输出都是"不能为空",不能根据categoryName、categoryDir的不同而显示不同的信息,想让categoryName输出"categoryName不能为空",让categoryDir输出"categoryDir不能为空",不知道有没有相关的变量可以做到?

回复内容:

<code>namespace backend\modules\article\models;
use yii\db\ActiveRecord;

class Category extends ActiveRecord
{
    
    public static function tableName()
    {
        return 'category';
    }
    
    public function rules()
    {
        return [
            [['categoryName','categoryDir'],'required','message'=>'不能为空']
        ];
    }

}</code>

上面定义的错误信息,输出都是"不能为空",不能根据categoryName、categoryDir的不同而显示不同的信息,想让categoryName输出"categoryName不能为空",让categoryDir输出"categoryDir不能为空",不知道有没有相关的变量可以做到?

我想你需要的是这个:

<code>[['username', 'password'], 'required', 'message' => '{attribute}不能为空!'],</code>

<code> public function rules()
    {
        return [
            ['categoryName','required','message'=>'categoryName不能为空'],
            ['categoryDir','required','message'=>'categoryDir不能为空']
        ];
    }</code>

这样可以吗?

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn