Skip to content
This repository was archived by the owner on Mar 13, 2025. It is now read-only.
18 changes: 15 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
# Yet Another PHP Validator

Versatile library focused on validating development code with expressive error messages.
PHP validator focused on validating development code with expressive error messages.

> **Note**
> This library is not in version 1.x mainly because there are few available rules.
> Hopefully, that will change in the near future.

## Requirements

Expand Down Expand Up @@ -44,15 +48,23 @@ $validator->assert(16, 'Age'); // throws exception: The "Age" value should be gr

## Documentation

- [Get Started](docs/01-get-started.md)
- [Usage](docs/02-usage.md)
- [Usage](docs/02-usage.md#usage)
- [Methods](docs/02-usage.md#methods)
- [Error Handling](docs/02-usage.md#error-handling)
- [Custom Error Messages](docs/02-usage.md#custom-error-messages)
- [Rules](docs/03-rules.md)
- [Custom Rules](docs/04-custom-rules.md)

## Contributing

Any form of contribution to improve this library will be welcome and appreciated.
Any form of contribution to improve this library (including requests) will be welcome and appreciated.
Make sure to open a pull request or issue.

## Acknowledgments

This library is inspired by [Respect's Validation](https://github.com/Respect/Validation) and [Symfony's Validator](https://symfony.com/doc/current/validation.html).
This library is inspired by [respect/validation](https://github.com/Respect/Validation) and [symfony/validator](https://github.com/symfony/validator).

## License

Expand Down
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"name": "programmatordev/yet-another-php-validator",
"description": "PHP Validator",
"description": "PHP validator focused on validating development code with expressive error messages",
"type": "library",
"keywords": ["PHP", "Validator", "Validation"],
"keywords": ["PHP", "PHP8", "Validator", "Validation"],
"license": "MIT",
"authors": [
{
Expand Down
9 changes: 2 additions & 7 deletions docs/01-get-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,13 @@ use ProgrammatorDev\YetAnotherPhpValidator\Validator;
// Do this...
$validator = Validator::notBlank()->greaterThanOrEqual(18);

// ...or this...
// Or this...
$validator = new Validator(
new Rule\NotBlank(),
new Rule\GreaterThanOrEqual(18)
);

// ...or even this...
$validator = (new Validator())
->addRule(new Rule\NotBlank())
->addRule(new Rule\GreaterThanOrEqual(18));

// ...and validate with these:
// Validate with these:
$validator->validate(16); // returns bool: false
$validator->assert(16, 'Age'); // throws exception: The "Age" value should be greater than or equal to "18", "16" given.
```
101 changes: 81 additions & 20 deletions docs/02-usage.md
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
# Using Yet Another PHP Validator

- Usage
- Fluent
- Dependency Injection
- Methods
- assert
- validate
- getRules
- addRule
- Exception Handling
- Custom Exception Messages
- [Usage](#usage)
- [Fluent](#fluent)
- [Dependency Injection](#dependency-injection)
- [Methods](#methods)
- [assert](#assert)
- [validate](#validate)
- [getRules](#getrules)
- [addRule](#addrule)
- [Error Handling](#error-handling)
- [Custom Error Messages](#custom-error-messages)

## Usage

This library allows you to use validate data in two different ways:
This library allows you to validate data in two different ways:
- In a fluent way, making use of magic methods. The goal is to be able to create a set of rules with minimum setup;
- In a traditional way, making use of dependency injection. You may not like the fluent approach, and prefer to work this way.

Expand Down Expand Up @@ -71,7 +71,7 @@ This method throws a `ValidationException` when a rule fails, otherwise nothing
assert(mixed $value, string $name): void;
```

An example on how to handle an exception:
An example on how to handle an error:

```php
use ProgrammatorDev\YetAnotherPhpValidator\Exception\ValidationException;
Expand All @@ -93,9 +93,11 @@ catch (ValidationException $exception) {
echo $exception->getMessage(); // The "Latitude" value should be between "-90" and "90", "100" given.
}
```
> **Note**
> Check the [Error Handling](#error-handling) section for more information.

> **Note**
> The example only shows one usage approach, but both Fluent and Dependency Injection usage approaches should work the same.
> The example only shows one usage approach, but both Fluent and Dependency Injection should work the same.
> Check the [Usage](#usage) section for more information.

### `validate`
Expand All @@ -117,7 +119,7 @@ if (!Validator::range(-90, 90)->validate($latitude)) {
```

> **Note**
> The example only shows one usage approach, but both Fluent and Dependency Injection usage approaches should work the same.
> The example only shows one usage approach, but both Fluent and Dependency Injection should work the same.
> Check the [Usage](#usage) section for more information.

### `getRules`
Expand Down Expand Up @@ -148,7 +150,7 @@ print_r($validator->getRules());
```

> **Note**
> The example only shows one usage approach, but both Fluent and Dependency Injection usage approaches should work the same.
> The example only shows one usage approach, but both Fluent and Dependency Injection should work the same.
> Check the [Usage](#usage) section for more information.

### `addRule`
Expand Down Expand Up @@ -180,16 +182,75 @@ function calculateDiscount(float $price, float $discount, string $type): float
```

> **Note**
> The example only shows one usage approach, but both Fluent and Dependency Injection usage approaches should work the same.
> The example only shows one usage approach, but both Fluent and Dependency Injection should work the same.
> Check the [Usage](#usage) section for more information.

## Exception Handling
## Error Handling

When using the [`assert`](#assert) method, an exception is thrown when a rule fails.

Each rule has a unique exception, formed by the name of the rule followed by the word Exception, like `RuleNameException`.
The following shows an example:

```php
use ProgrammatorDev\YetAnotherPhpValidator\Exception;
use ProgrammatorDev\YetAnotherPhpValidator\Validator;

try {
Validator::range(-90, 90)->assert($latitude, 'Latitude');
Validator::range(-180, 180)->assert($longitude, 'Longitude');
Validator::notBlank()->choice(['METRIC', 'IMPERIAL'])->assert($unitSystem, 'Unit System');
}
catch (Exception\RangeException $exception) {
// Do something when Range fails
}
catch (Exception\NotBlankException $exception) {
// Do something when NotBlank fails
}
catch (Exception\ChoiceException $exception) {
// Do something when Choice fails
}
```

To catch all errors with a single exception, you can use the `ValidationException`:

```php
use ProgrammatorDev\YetAnotherPhpValidator\Exception\ValidationException;
use ProgrammatorDev\YetAnotherPhpValidator\Validator;

try {
Validator::range(-90, 90)->assert($latitude, 'Latitude');
Validator::range(-180, 180)->assert($longitude, 'Longitude');
Validator::notBlank()->choice(['METRIC', 'IMPERIAL'])->assert($unitSystem, 'Unit System');
}
catch (ValidationException $exception) {
// Do something when a rule fails
echo $exception->getMessage();
}
```

When using both the [`assert`](#assert) or [`validate`](#validate) methods,
an `UnexpectedValueException` is thrown when the provided input data is not valid to perform the validation.

For example, when trying to compare a date with a string:

```php
use ProgrammatorDev\YetAnotherPhpValidator\Exception\UnexpectedValueException;
use ProgrammatorDev\YetAnotherPhpValidator\Validator;

try {
Validator::greaterThanOrEqual(new DateTime('today'))->validate('alpha');
}
catch (UnexpectedValueException $exception) {
echo $exception->getMessage(); // Cannot compare a type "string" with a type "DateTime".
}
```

## Custom Exception Messages
## Custom Error Messages

All rules have at least one error message that can be customized (some rules have more than one error message for different case scenarios).

Every message has a list of dynamic parameters to help create an intuitive error text (like the invalid value, constraints, names, and others).
Every message has a list of dynamic parameters to help create an intuitive error (like the invalid value, constraints, names, and others).
To check what parameters and messages are available, look into the Options section in the page of a rule.
Go to [Rules](03-rules.md) to see all available rules.

Expand All @@ -203,5 +264,5 @@ Validator::choice(
message: '"{{ value }}" is not a valid {{ name }}! You must select one of {{ constraints }}.'
)->assert('yellow', 'color');

// "yellow" is not a valid color! You must select one of [red, green, blue].
// Throws: "yellow" is not a valid color! You must select one of [red, green, blue].
```
4 changes: 2 additions & 2 deletions docs/03-rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
- [Basic Rules](#basic-rules)
- [Comparison Rules](#comparison-rules)
- [Choice Rules](#choice-rules)
- [Array Rules](#array-rules)
- [Other Rules](#other-rules)

## Basic Rules

Expand All @@ -21,6 +21,6 @@

- [Choice](03x-rules-choice.md)

## Array Rules
## Other Rules

- [All](03x-rules-all.md)
2 changes: 1 addition & 1 deletion docs/03x-rules-all.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,6 @@ The following parameters are available:
| Parameter | Description |
|-----------------|-----------------------------------------------|
| `{{ value }}` | The current invalid value |
| `{{ name }}` | Name of the value being validated |
| `{{ name }}` | Name of the invalid value |
| `{{ key }}` | The array key of the invalid array element |
| `{{ message }}` | The rule message of the invalid array element |
26 changes: 13 additions & 13 deletions docs/03x-rules-choice.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ Validator::choice(['red', 'green', 'blue'], multiple: true, minConstraint: 2, ma

type: `array` `required`

Collection of choices to be validated against the input value.
Collection of constraint choices to be validated against the input value.

### `multiple`

Expand Down Expand Up @@ -84,11 +84,11 @@ Message that will be shown if input value is not a valid choice.

The following parameters are available:

| Parameter | Description |
|---------------------|-----------------------------------|
| `{{ value }}` | The current invalid value |
| `{{ name }}` | Name of the value being validated |
| `{{ constraints }}` | The array of valid choices |
| Parameter | Description |
|---------------------|----------------------------|
| `{{ value }}` | The current invalid value |
| `{{ name }}` | Name of the invalid value |
| `{{ constraints }}` | The array of valid choices |

### `multipleMessage`

Expand All @@ -98,11 +98,11 @@ Message that will be shown when `multiple` is `true` and at least one of the inp

The following parameters are available:

| Parameter | Description |
|---------------------|-----------------------------------|
| `{{ value }}` | The current invalid value |
| `{{ name }}` | Name of the value being validated |
| `{{ constraints }}` | The array of valid choices |
| Parameter | Description |
|---------------------|----------------------------|
| `{{ value }}` | The current invalid value |
| `{{ name }}` | Name of the invalid value |
| `{{ constraints }}` | The array of valid choices |

### `minMessage`

Expand All @@ -116,7 +116,7 @@ The following parameters are available:
|-----------------------|--------------------------------------|
| `{{ value }}` | The current invalid value |
| `{{ numValues }}` | The current invalid number of values |
| `{{ name }}` | Name of the value being validated |
| `{{ name }}` | Name of the invalid value |
| `{{ constraints }}` | The array of valid choices |
| `{{ minConstraint }}` | The minimum number of valid choices |
| `{{ maxConstraint }}` | The maximum number of valid choices |
Expand All @@ -133,7 +133,7 @@ The following parameters are available:
|-----------------------|--------------------------------------|
| `{{ value }}` | The current invalid value |
| `{{ numValues }}` | The current invalid number of values |
| `{{ name }}` | Name of the value being validated |
| `{{ name }}` | Name of the invalid value |
| `{{ constraints }}` | The array of valid choices |
| `{{ minConstraint }}` | The minimum number of valid choices |
| `{{ maxConstraint }}` | The maximum number of valid choices |
12 changes: 6 additions & 6 deletions docs/03x-rules-greater-than-or-equal.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ Validator::greaterThanOrEqual(new DateTime('today'))->validate(new DateTime('tod
```

> **Note**
> String comparison is case-sensitive, meaning that comparing `'hello'` with `'Hello'` is different.
> String comparison is case-sensitive, meaning that comparing `"hello"` with `"Hello"` is different.
> Check [`strcmp`](https://www.php.net/manual/en/function.strcmp.php) for more information.

> **Note**
Expand All @@ -50,8 +50,8 @@ Message that will be shown if the value is not greater than or equal to the cons

The following parameters are available:

| Parameter | Description |
|--------------------|-----------------------------------|
| `{{ value }}` | The current invalid value |
| `{{ name }}` | Name of the value being validated |
| `{{ constraint }}` | The comparison value |
| Parameter | Description |
|--------------------|---------------------------|
| `{{ value }}` | The current invalid value |
| `{{ name }}` | Name of the invalid value |
| `{{ constraint }}` | The comparison value |
12 changes: 6 additions & 6 deletions docs/03x-rules-greater-than.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ Validator::greaterThan(new DateTime('today'))->validate(new DateTime('today'));
```

> **Note**
> String comparison is case-sensitive, meaning that comparing `'hello'` with `'Hello'` is different.
> String comparison is case-sensitive, meaning that comparing `"hello"` with `"Hello"` is different.
> Check [`strcmp`](https://www.php.net/manual/en/function.strcmp.php) for more information.
> **Note**
Expand All @@ -50,8 +50,8 @@ Message that will be shown if the value is not greater than the constraint value

The following parameters are available:

| Parameter | Description |
|--------------------|-----------------------------------|
| `{{ value }}` | The current invalid value |
| `{{ name }}` | Name of the value being validated |
| `{{ constraint }}` | The comparison value |
| Parameter | Description |
|--------------------|---------------------------|
| `{{ value }}` | The current invalid value |
| `{{ name }}` | Name of the invalid value |
| `{{ constraint }}` | The comparison value |
12 changes: 6 additions & 6 deletions docs/03x-rules-less-than-or-equal.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ Validator::lessThanOrEqual(new DateTime('today'))->validate(new DateTime('today'
```

> **Note**
> String comparison is case-sensitive, meaning that comparing `'hello'` with `'Hello'` is different.
> String comparison is case-sensitive, meaning that comparing `"hello"` with `"Hello"` is different.
> Check [`strcmp`](https://www.php.net/manual/en/function.strcmp.php) for more information.

> **Note**
Expand All @@ -50,8 +50,8 @@ Message that will be shown if the value is not less than or equal to the constra

The following parameters are available:

| Parameter | Description |
|--------------------|-----------------------------------|
| `{{ value }}` | The current invalid value |
| `{{ name }}` | Name of the value being validated |
| `{{ constraint }}` | The comparison value |
| Parameter | Description |
|--------------------|---------------------------|
| `{{ value }}` | The current invalid value |
| `{{ name }}` | Name of the invalid value |
| `{{ constraint }}` | The comparison value |
Loading