Yii 1.1: How to customize the error message of a validation rule


Validators extending from CValidator all have a property named message. You can set this property in the corresponding validation rule to customize the error message. For example, the following validation rule uses an error message that is different from the default one:

class Post extends CActiveRecord
    public function rules()
        return array(
            array('title, content', 'required',
                  'message'=>'Please enter a value for {attribute}.'),
            // ... other rules

In the above, the customized error message contains a predefined placeholder {attribute}. The CRequiredValidator (whose alias is required) will replace this placeholder with the actual attribute name that fails the validation.

Total 4 comments

#16172 report it
Nabi at 2014/01/25 09:34pm
How can customize messages for any rule of File?

About File rule, There are more then one rule. some rules is for "types", "allowEmpty", "maxSize",... Now how can customize messages for any rule of File?

Answer: Can use "tooLarge", "tooMany", "tooSmall", "wrongMimeType", "wrongType", ... methods. re: http://www.yiiframework.com/doc/api/1.1/CFileValidator

#7068 report it
Don Felipe at 2012/02/22 06:38am
Placeholder values

Here's a list of many placeholders and the validators that are using them:

  • CBooleanValidator: {true} {false}
  • CCaptchaValidator: {id}
  • CCompareValidator: {compareAttribute} {compareValue} {operator}
  • CExistValidator: {table} {column} {value}
  • CFileValidator: {file} {limit} {extensions}
  • CNumberValidator: {min} {max}
  • CRequiredValidator: {value}
  • CStringValidator: {min} {max} {length}
  • CTypeValidator: {type}
  • CUniqueValidator: {table} {column} {value}
  • CUrlValidator: {schemes}

Of course, {attribute} is known in all validators. So, which placeholders are known depends on the validator and the condition as well: By default {min} is only used when the value is below the min value (as defined in rules) and {max} when the value is above the max value.

#4960 report it
ManInTheBox at 2011/09/01 06:39am
Re: Missing value

No, you SHOULD use {attribute} placeholder. Look for predefined {attribute} placeholder.

#4550 report it
phazei at 2011/07/19 03:37pm
Missign value

What about the value of the attribute? That is in default error messages. Shouldn't there be a {value} ?

Leave a comment

Please to leave your comment.

Write new article
  • Written by: qiang
  • Updated by: Yang He
  • Category: Tutorials
  • Yii Version: 1.1
  • Votes: +18 / -2
  • Viewed: 106,619 times
  • Created on: Feb 3, 2009
  • Last updated: Jun 29, 2012