Skip to content

Commit

Permalink
Merge pull request #13 from BlakvGhost/add-validation-error-message-l…
Browse files Browse the repository at this point in the history
…anguage-on-Validator-constructor

Add feature to add default language for validation message
  • Loading branch information
BlakvGhost authored Dec 9, 2023
2 parents d57663e + 3a3539c commit 8195f32
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 22 deletions.
34 changes: 20 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@

</div>


## About PHPValidator

PHPValidator is a modern PHP library for data validation in your PHP applications. It provides a flexible and extensible way to validate data using predefined rules or by creating custom validation rules.
Expand Down Expand Up @@ -58,7 +57,8 @@ try {
}

```
You can also customize the validation error messages

You can also customize the validation error messages or `specify the default language`

```php
$data = [
Expand All @@ -77,6 +77,9 @@ $validator = new Validator(
],
]
);

// For the default language
$validator = new Validator($data, $rules, lang: 'fr');
```

## Features
Expand All @@ -87,7 +90,6 @@ $validator = new Validator(

- `Multilingual Support`: Customize validation error messages based on the application's language using the `LangManager`.


## List of Predefined Rules

PHPValidator provides a variety of predefined rules that you can use for data validation. Here is a list of some commonly used rules along with examples of their usage:
Expand Down Expand Up @@ -210,25 +212,27 @@ PHPValidator provides a variety of predefined rules that you can use for data va
```php
'password_confirmation' => 'same:password'
```

18. **Max Length Rule**
- Specifies the minimum length of a string field.

```php
'username' => 'min:8'
```
```

19. **Not In Rule**
- Validates that a field's value is not in a specified set.

```php
'value' => 'not_in:foo,bar'
```
```

20. **Required With Rule**
- Requires the field to be present if another specified field is present.


```php
'firstname' => 'required_with:lastname',
```
```

21. **Valid IP Rule**
- Validates that a field's value is a valid IP address.
Expand All @@ -242,29 +246,30 @@ PHPValidator provides a variety of predefined rules that you can use for data va

```php
'config' => 'json',
```
```

23. **URL Rule**
- Validates that a field's value is a valid URL.

```php
'website' => 'url',
```
```

24. **Alpha Numeric Rule**

- Validates that a field's value contains only alphanumeric characters.

```php
'pseudo' => 'alpha_num',
```
```

25. **Boolean Rule**

- Validates that a field's value is a boolean.

```php
'is_admin' => 'bool',
```
```

26. **Size Rule**
- Validates that the size of a string, integer, array, or file is equal to a specified value.
Expand All @@ -276,7 +281,8 @@ PHPValidator provides a variety of predefined rules that you can use for data va
'array' =>'size:7', // count(array) == 7
'file' =>'size:512', // file size (kb) == 512
]
```
```

## Custom Rule

In addition to the predefined rules, you can create custom validation rules by implementing the `Rule` Interface. Here's an example of how to create and use a custom rule:
Expand Down Expand Up @@ -311,6 +317,7 @@ class CustomPasswordRule implements Rule
}
}
```

### Usage in Validator

- Use your custom class directly
Expand Down Expand Up @@ -348,6 +355,7 @@ class CustomPasswordRule implements Rule
echo "Validation error: " . $e->getMessage();
}
```

- Add your custom class to the rules list and use it as if it were native

```php
Expand Down Expand Up @@ -393,12 +401,10 @@ If you would like to contribute to PHPValidator, please follow our [Contribution

- [Kabirou ALASSANE](https://github.com/BlakvGhost)


## Support

For support, you can reach out to me by email at <dev@kabirou-alassane.com>. Feel free to contact me if you have any questions or need assistance with PHPValidator.

## License

PHPValidator is open-source software licensed under the MIT license.

4 changes: 2 additions & 2 deletions src/Lang/Lang.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ trait Lang
'validation.required_with' => "Le champ :attribute est requis avec le champ :value.",
'validation.max_length_rule' => "Le champ :attribute ne doit pas dépasser :max caractères.",
'validation.min_length_rule' => "Le champ :attribute doit dépasser :min caractères.",
'validation.email_rule' => "Le champ :attribute doit être un e-mail.",
'validation.email_rule' => "Le champ :attribute doit être un e-mail valide.",
'validation.accepted' => "Le champ :attribute doit être accepté.",
'validation.accepted_if' => "Le champ :attribute doit être accepté uniquement si :other existe et vrai.",
'validation.same_rule' => "Le champ :attribute doit être identique au champ :otherAttribute.",
Expand Down Expand Up @@ -60,7 +60,7 @@ trait Lang
'validation.required_with' => "The :attribute field is required along with the :value field.",
'validation.max_length_rule' => "The :attribute field must not exceed :max characters.",
'validation.min_length_rule' => "The :attribute field must exceed :min characters.",
'validation.email_rule' => "The :attribute field must be an email.",
'validation.email_rule' => "The :attribute field must be a valid email.",
'validation.accepted' => "The :attribute field must be accepted.",
'validation.accepted_if' => "The :attribute field must be accepted if :other.",
'validation.same_rule' => "The :attribute field must be identical to the :otherAttribute field.",
Expand Down
4 changes: 3 additions & 1 deletion src/Lang/LangManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ class LangManager

use Lang;

static public $lang = 'en';

/**
* Get the current language.
*
Expand All @@ -24,7 +26,7 @@ class LangManager
private static function getLocal(): string
{
// Get the current language from environment variables, defaulting to 'en' (English) if not set.
return $_ENV['local'] ?? 'en';
return self::$lang ?? $_ENV['local'];
}

/**
Expand Down
16 changes: 12 additions & 4 deletions src/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@
class Validator extends RulesMaped
{

private $errors = [];
private array $errors = [];

private const LANGUAGE = 'en';

/**
* Constructor of the Validator class.
Expand All @@ -31,8 +33,10 @@ class Validator extends RulesMaped
public function __construct(
private array $data,
private array $rules,
private array $messages = []
private array $messages = [],
private string $lang = self::LANGUAGE,
) {
LangManager::$lang = $this->lang;
$this->validateConstructorInputs();
$this->validate();
}
Expand Down Expand Up @@ -137,11 +141,15 @@ protected function checkPasses(mixed $validator, string $field, ?string $ruleNam
protected function validateConstructorInputs()
{
if (empty($this->data)) {
throw new ValidatorException(LangManager::getTranslation('validation.empty_data'));
throw new ValidatorException(
LangManager::getTranslation('validation.empty_data')
);
}

if (empty($this->rules)) {
throw new ValidatorException(LangManager::getTranslation('validation.empty_rules'));
throw new ValidatorException(
LangManager::getTranslation('validation.empty_rules')
);
}
}

Expand Down
2 changes: 1 addition & 1 deletion tests/Feature/RuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
$validator = new Validator(['email' => 'test@example.com'], ['email' => 'email']);
expect($validator->isValid())->toBeTrue();

$validator = new Validator(['email' => 'invalid-email'], ['email' => 'email']);
$validator = new Validator(['email' => 'invalid-email'], ['email' => 'email'], lang:'fr');
expect($validator->isValid())->toBeFalse();

expect($validator->getErrors()['email'][0])->toBe(
Expand Down

0 comments on commit 8195f32

Please sign in to comment.