Skip to content

Bug: localised validation messages #2845

Closed
@alex-misch

Description

@alex-misch

Hello

I didn't find any way to localise field interpolation in validation messages in models. It looks like a bug. Sorry if I'm wrong. Now I wrote little workaround. I`ll leave it below but in my opinion its looks bad. In CodeIgniter v3 I've loaded two lang files in controller and {field} was replaced to localised value automatically.

Affected module(s)

  • Model
  • Validation

Expected behavior, and steps to reproduce if appropriate

File structure:

Language/en/Validation.php:

return ['valid_date' => 'Field {field} is invalid'];

Language/en/Entity.php:

return ['date' => 'My localised date label'];

Models/MyModel.php:

class MyModel extends Model {
	protected $validationRules = [
		"date_start" => [
			"rules" => "valid_date", "label" => "Entity.date"
		],
	];
}

Now call model validation in controller in controller:

class MyController extends Controller
{
	function index() {
		$model = model(\App\Models\MyModel::class);
		$model->insert(['date_start' => 'invalid date']);
		echo $model->getErrors();
	}
}

And you've got response

["date" => "Field Entity.date is invalid"];

So how to localise Entity.date field?

Workaround

class LocalisedModel extends Model
{
	public function __construct(...$args)
	{
		parent::__construct(...$args);
		$this->validationRules = array_map(function ($rule) {
			if (is_array($rule) && $rule['label']) {
				$rule['label'] = lang($rule['label']);
			}
			return $rule;
		}, $this->validationRules);
	}
}

Context

  • OS: CentOS
  • Web server Apache 2.4.43
  • PHP version 7.2

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugVerified issues on the current code behavior or pull requests that will fix them

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions