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: validation




August 6th, 2009 at 6:53 pm
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.
August 6th, 2009 at 7:22 pm
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.
August 12th, 2009 at 4:20 am
[...] http://cake.eizoku.com/blog/?p=30#comment-8 [...]
September 4th, 2009 at 7:33 pm
Simple its always good
Thanks for your idea and for taking your time to explain it here.
September 27th, 2009 at 4:51 am
Great site, how do I subscribe?
February 19th, 2010 at 5:36 pm
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!
May 29th, 2010 at 3:22 am
Thanks to Marcel Gordon to this clever and easy solution!