Validation error message i18n

In a Model, we can define validation error message as follow

<?php
class User extends AppModel {
	var $validate = array(
		'email' => array(
			"email_invalid" => array('rule' => VALID_EMAIL,
				'required' => true,
				'message'    =>    'Invalid Email address.',
	),

But, can not use i18n function __() for validation error messages .
This is a solution to do it.

<?php
class AppModel extends Model {

	//Validation message i18n
	function invalidate($field, $value = true){
		parent::invalidate($field, $value);
		$this->validationErrors[$field] = __($value, true);
	}
}

Model::invalidate method is called in validation processing(Model::validates , Model::invalidFields).
This solution override Model::invalidate and set __() in each error messsage.

Then, you write po file of each language, language of validation error messages change depending on browser language configuration.

Tags:

7 Responses to “Validation error message i18n”

  1. Marcel Gordon Says:

    I build a lot of multi-lingual sites so I’ve run into this problem before. The one problem with your solution is that the actual error messages are not contained within the __() function which makes it difficult to extract them automatically from the code using a shell, poedit or similar.

    Here’s what I did instead:

    In the model, instead of defining var $validate = array(…) I defined a new function

    function loadValidation() {
    $this->validate = array(
    ‘date’ => array(
    ‘rule’ => ‘date’,
    ‘required’ => false,
    ‘allowEmpty’ => false,
    ‘message’ => __(’Please enter a valid date’, true)
    );
    }

    The in app_model.php:

    function beforeValidate() {
    $this->loadValidation();
    return true;
    }

    Now you can put strings to be translated directly into the validation rules where they can be extracted automatically.

  2. ichikaway Says:

    Hi, Marcel . Thank you for your comment.

    Recently, I think same topic, how to extracting validation error messages using “cake i18n” command.
    Your idea is so simple and nice! Thanks.

  3. internationalization in model Says:

    [...] http://cake.eizoku.com/blog/?p=30#comment-8 [...]

  4. almail985 Says:

    Simple its always good :) Thanks for your idea and for taking your time to explain it here.

  5. Kelli Garner Says:

    Great site, how do I subscribe?

  6. cosmin Says:

    I’ve been in the i18n valley too but got put quite ok thanks to Cake :)
    You can always specify the messages in the $form->input methods inside the views. Because the messages are really a job for the V and the validation rules a job for the M this technique is well worth considering.
    All the best!

  7. countach Says:

    Thanks to Marcel Gordon to this clever and easy solution!

Leave a Reply