更改Yii自定义表单验证程序错误消息{attribute}

时间:2013-04-14 17:31:53

标签: yii

我可以在我的模型中通过这些代码更改表单验证器错误消息:

array('name, email, subject, body', 'required'
                        'message'=>'Please enter a value for {attribute}.'),

但我不知道{attribute}来自哪里以及我如何为每个字段更改它,所以任何帮助都会受到赞赏。

3 个答案:

答案 0 :(得分:5)

我不确定我是否理解你的问题,但你问{attribute}来自哪里:

有些验证器会在您的示例中引入占位符,例如{attribute}。如果验证失败,它们将替换为属性名称。因此,如果未输入name且您的message'Please enter a valid {attribute}.',则错误消息将为“请输入有效名称”。

虽然{attribute}占位符可以与每个验证器一起使用,但其中一些占位符会引入更多占位符。例如,使用CStringValidator,您可以使用{min}{max}{length}。它们将分别替换为最小最大完全字符的数量。

以下是一个例子:

array('firstname,lastname', 'string', 'min'=>3, 
    'tooShort'=>'Your {attribute} must contain at least {min} letters.'
),

如果用户输入少于3个字母,则会显示“您的名字必须包含至少3个字母。”。这样做的好处是,如果您更改min参数,您的消息将自动更新。所以它不容易出错。

答案 1 :(得分:4)

使用这些:

return array(
    // name, email, subject and body are required
    array('name', 'required',
                'message'=>'Please enter a value for name.'),
    array('email', 'required',
                'message'=>'Please enter a value for email.'),
    array('subject', 'required',
                'message'=>'Please enter a value for subject.'),
    array('body', 'required',
                'message'=>'Please enter a value for body.'),

答案 2 :(得分:2)

{attribute}来自您的函数:

    public function attributeLabels() {
    return array(
        'id' => 'ID',
        'name' => 'Name',
        'password' => 'Password',
        'email' => 'Email',

    );
}

在你的模特身上。