Oihana PHP System

I18nRule extends Rule

Validates a multilingual (i18n) field ensuring: - Only allowed language codes are present.

  • Values are strings or null.

This rule can validate arrays or objects containing translations. It is useful for payloads like:

$payload =
[
    'description' =>
    [
        'fr' => 'Bonjour',
        'en' => 'Hello',
        'de' => null
    ]
];

You can restrict which languages are valid by passing an array or a single language code to the constructor:

$rule = new I18nRule(['fr', 'en']);

Usage Examples

use Somnambulist\Components\Validation\Factory;
use oihana\validations\rules\I18nRule;

$validator = new Factory();
$validator->addRule('i18n', new I18nRule(['fr','en']));

$payload = ['description' => ['fr'=>'Bonjour','en'=>'Hello']];
$validation = $validator->validate($payload, ['description' => 'required|i18n']);

$validation->passes(); // true

$payload = ['description' => ['fr'=>'Bonjour','de'=>'Hallo']];
$validation = $validator->validate($payload, ['description' => 'required|i18n']);

$validation->passes(); // false, 'de' not allowed
Tags
author

Marc Alcaraz (ekameleon)

since
1.0.0

Table of Contents

Constants

LANGUAGES  = 'languages'
The 'languages' parameter key.

Properties

$fillableParams  : array<string|int, mixed>|array<string|int, string>
The list of required parameters.
$message  : string
The error message used when validation fails.

Methods

__construct()  : mixed
Creates a new LanguagesRule instance.
check()  : bool
Validates that each field in the payload contains only allowed languages and that values are string or null.
languages()  : static
Sets allowed languages.

Constants

LANGUAGES

The 'languages' parameter key.

public mixed LANGUAGES = 'languages'

Properties

$fillableParams

The list of required parameters.

protected array<string|int, mixed>|array<string|int, string> $fillableParams = [self::LANGUAGES]

$message

The error message used when validation fails.

protected string $message = ':attribute contains invalid translations or unsupported languages.'

Methods

__construct()

Creates a new LanguagesRule instance.

public __construct([array<string|int, mixed>|string|null $languages = null ]) : mixed
Parameters
$languages : array<string|int, mixed>|string|null = null

Array or list of allowed language codes.

check()

Validates that each field in the payload contains only allowed languages and that values are string or null.

public check(mixed $value) : bool
Parameters
$value : mixed

array/object of translations

Tags
throws
ParameterException
Return values
bool

languages()

Sets allowed languages.

public languages(array<string|int, mixed>|string|null $languages) : static
Parameters
$languages : array<string|int, mixed>|string|null
Return values
static

        
On this page

Search results