Enhancing validation messages to have placeholders. Closes #1855

This commit is contained in:
ADmad 2011-07-31 06:33:56 +05:30
parent f9373ff504
commit b15c77ecc3
5 changed files with 59 additions and 7 deletions

View file

@ -390,7 +390,12 @@ class ExtractTask extends Shell {
foreach ($rules as $rule => $validateProp) {
if (isset($validateProp['message'])) {
$this->_strings[$domain][$validateProp['message']][$file][] = 'validation for field ' . $field;
if (is_array($validateProp['message'])) {
$message = $validateProp['message'][0];
} else {
$message = $validateProp['message'];
}
$this->_strings[$domain][$message][$file][] = 'validation for field ' . $field;
}
}
}

View file

@ -2754,6 +2754,13 @@ class Model extends Object {
} else {
$validator['message'] = __d($validationDomain, $message);
}
} elseif (is_array($validator['message'])) {
if (count($validator['message']) > 1) {
$args = array_slice($validator['message'], 1);
} else {
$args = $validator['rule'];
}
$validator['message'] = __d($validationDomain, $validator['message'][0], $args);
}
$this->invalidate($fieldName, $validator['message']);

View file

@ -293,6 +293,9 @@ class ExtractTaskTest extends CakeTestCase {
$pattern = '#msgid "Post title is required"#';
$this->assertPattern($pattern, $result);
$pattern = '#msgid "You may enter up to %s chars \(minimum is %s chars\)"#';
$this->assertPattern($pattern, $result);
$pattern = '#msgid "Post body is required"#';
$this->assertPattern($pattern, $result);

View file

@ -682,4 +682,35 @@ class ModelValidationTest extends BaseModelTest {
$this->assertEquals($TestModel->validationErrors, array());
}
/**
* Test placeholder replacement when validation message is an array
*
* @return void
*/
public function testValidationMessageAsArray() {
$TestModel = new ValidationTest1();
$TestModel->create(array('title' => 'foo'));
$TestModel->validate = array(
'title' => array(
'minLength' => array(
'rule' => array('minLength', 6),
'message' => array('Minimum length allowed is %d chars'),
'last' => false
),
'between' => array(
'rule' => array('between', 5, 15),
'message' => array('You may enter up to %s chars (minimum is %s chars)', 14, 6)
)
)
);
$TestModel->invalidFields();
$expected = array(
'title' => array(
'Minimum length allowed is 6 chars',
'You may enter up to 14 chars (minimum is 6 chars)'
)
);
$this->assertEquals($TestModel->validationErrors, $expected);
}
}

View file

@ -27,11 +27,17 @@ class PersisterOne extends AppModel {
public $hasMany = array('Comment', 'TestPlugin.TestPluginComment');
public $validate = array(
'title' => array(
'custom' => array(
'rule' => array('custom', '.*'),
'allowEmpty' => true,
'required' => false,
'message' => 'Post title is required'
),
'between' => array(
'rule' => array('between', 5, 15),
'message' => array('You may enter up to %s chars (minimum is %s chars)', 14, 6)
)
),
'body' => array(
'first_rule' => array(
'rule' => array('custom', '.*'),