Skip to content

Commit ff003a3

Browse files
authored
Merge pull request #126 from devhammed/feat/add-boolean-rule
feat: add boolean rule to the core rules
2 parents 126306c + c52a4be commit ff003a3

File tree

4 files changed

+112
-45
lines changed

4 files changed

+112
-45
lines changed

README.md

Lines changed: 50 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,8 @@ composer require "rakit/validation"
3232

3333
#### Usage
3434

35-
There are two ways to validating data with this library. Using `make` to make validation object,
36-
then validate it using `validate`. Or just use `validate`.
35+
There are two ways to validating data with this library. Using `make` to make validation object,
36+
then validate it using `validate`. Or just use `validate`.
3737
Examples:
3838

3939
Using `make`:
@@ -112,7 +112,7 @@ if ($validation->fails()) {
112112

113113
```
114114

115-
In this case, 2 examples above will output the same results.
115+
In this case, 2 examples above will output the same results.
116116

117117
But with `make` you can setup something like custom invalid message, custom attribute alias, etc before validation running.
118118

@@ -234,7 +234,7 @@ $validation_a->validate();
234234

235235
#### Custom Message for Specific Attribute Rule
236236

237-
Sometimes you may want to set custom message for specific rule attribute.
237+
Sometimes you may want to set custom message for specific rule attribute.
238238
To do this you can use `:` as message separator or using chaining methods.
239239

240240
Examples:
@@ -270,12 +270,12 @@ $validation_a->validate();
270270

271271
## Translation
272272

273-
Translation is different with custom messages.
273+
Translation is different with custom messages.
274274
Translation may needed when you use custom message for rule `in`, `not_in`, `mimes`, and `uploaded_file`.
275275

276-
For example if you use rule `in:1,2,3` we will set invalid message like "The Attribute only allows '1', '2', or '3'"
276+
For example if you use rule `in:1,2,3` we will set invalid message like "The Attribute only allows '1', '2', or '3'"
277277
where part "'1', '2', or '3'" is comes from ":allowed_values" tag.
278-
So if you have custom Indonesian message ":attribute hanya memperbolehkan :allowed_values",
278+
So if you have custom Indonesian message ":attribute hanya memperbolehkan :allowed_values",
279279
we will set invalid message like "Attribute hanya memperbolehkan '1', '2', or '3'" which is the "or" word is not part of Indonesian language.
280280

281281
So, to solve this problem, we can use translation like this:
@@ -295,7 +295,7 @@ $validation = $validator->validate($inputs, [
295295
'nomor' => 'in:1,2,3'
296296
]);
297297

298-
$message = $validation->errors()->first('nomor'); // "Nomor hanya memperbolehkan '1', '2', atau '3'"
298+
$message = $validation->errors()->first('nomor'); // "Nomor hanya memperbolehkan '1', '2', atau '3'"
299299
```
300300

301301
> Actually, our built-in rules only use words 'and' and 'or' that you may need to translates.
@@ -319,7 +319,7 @@ Get all messages as flatten array.
319319
Examples:
320320

321321
```php
322-
$messages = $errors->all();
322+
$messages = $errors->all();
323323
// [
324324
// 'Email is not valid email',
325325
// 'Password minimum 6 character',
@@ -341,7 +341,7 @@ Get only first message from all existing keys.
341341
Examples:
342342

343343
```php
344-
$messages = $errors->firstOfAll();
344+
$messages = $errors->firstOfAll();
345345
// [
346346
// 'email' => Email is not valid email',
347347
// 'password' => 'Password minimum 6 character',
@@ -354,13 +354,13 @@ $messages = $errors->firstOfAll('<li>:message</li>');
354354
// ]
355355
```
356356

357-
Argument `$dotNotation` is for array validation.
357+
Argument `$dotNotation` is for array validation.
358358
If it is `false` it will return original array structure, if it `true` it will return flatten array with dot notation keys.
359359

360360
For example:
361361

362362
```php
363-
$messages = $errors->firstOfAll(':message', false);
363+
$messages = $errors->firstOfAll(':message', false);
364364
// [
365365
// 'contacts' => [
366366
// 1 => [
@@ -470,7 +470,7 @@ The field under this validation must be present and not 'empty'.
470470
Here are some examples:
471471

472472
| Value | Valid |
473-
|---------------|-------|
473+
| ------------- | ----- |
474474
| `'something'` | true |
475475
| `'0'` | true |
476476
| `0` | true |
@@ -524,18 +524,18 @@ The field under validation must be present and not empty only when all of the ot
524524

525525
<details><summary><strong>uploaded_file</strong>:min_size,max_size,extension_a,extension_b,...</summary>
526526

527-
This rule will validate data from `$_FILES`.
527+
This rule will validate data from `$_FILES`.
528528
Field under this rule must be follows rules below to be valid:
529529

530-
* `$_FILES['key']['error']` must be `UPLOAD_ERR_OK` or `UPLOAD_ERR_NO_FILE`. For `UPLOAD_ERR_NO_FILE` you can validate it with `required` rule.
530+
* `$_FILES['key']['error']` must be `UPLOAD_ERR_OK` or `UPLOAD_ERR_NO_FILE`. For `UPLOAD_ERR_NO_FILE` you can validate it with `required` rule.
531531
* If min size is given, uploaded file size **MUST NOT** be lower than min size.
532532
* If max size is given, uploaded file size **MUST NOT** be higher than max size.
533533
* If file types is given, mime type must be one of those given types.
534534

535535
Here are some example definitions and explanations:
536536

537-
* `uploaded_file`: uploaded file is optional. When it is not empty, it must be `ERR_UPLOAD_OK`.
538-
* `required|uploaded_file`: uploaded file is required, and it must be `ERR_UPLOAD_OK`.
537+
* `uploaded_file`: uploaded file is optional. When it is not empty, it must be `ERR_UPLOAD_OK`.
538+
* `required|uploaded_file`: uploaded file is required, and it must be `ERR_UPLOAD_OK`.
539539
* `uploaded_file:0,1M`: uploaded file size must be between 0 - 1 MB, but uploaded file is optional.
540540
* `required|uploaded_file:0,1M,png,jpeg`: uploaded file size must be between 0 - 1MB and mime types must be `image/jpeg` or `image/png`.
541541

@@ -600,7 +600,7 @@ The `$_FILES` item under validation must have a MIME type corresponding to one o
600600

601601
<details><summary><strong>default/defaults</strong></summary>
602602

603-
This is special rule that doesn't validate anything.
603+
This is special rule that doesn't validate anything.
604604
It just set default value to your attribute if that attribute is empty or not present.
605605

606606
For example if you have validation like this
@@ -684,15 +684,15 @@ The field under this rule may have alpha characters, as well as spaces.
684684

685685
The field under this rule must be included in the given list of values.
686686

687-
This rule is using `in_array` to check the value.
688-
By default `in_array` disable strict checking.
687+
This rule is using `in_array` to check the value.
688+
By default `in_array` disable strict checking.
689689
So it doesn't check data type.
690690
If you want enable strict checking, you can invoke validator like this:
691691

692692
```php
693693
$validation = $validator->validate($data, [
694694
'enabled' => [
695-
'required',
695+
'required',
696696
$validator('in', [true, 1])->strict()
697697
]
698698
]);
@@ -712,7 +712,7 @@ This rule also using `in_array`. You can enable strict checking by invoking vali
712712

713713
<details><summary><strong>min</strong>:number</summary>
714714

715-
The field under this rule must have a size greater or equal than the given number.
715+
The field under this rule must have a size greater or equal than the given number.
716716

717717
For string value, size corresponds to the number of characters. For integer or float value, size corresponds to its numerical value. For an array, size corresponds to the count of the array. If your value is numeric string, you can put `numeric` rule to treat its size by numeric value instead of number of characters.
718718

@@ -731,7 +731,7 @@ $validation = $validator->validate([
731731

732732
<details><summary><strong>max</strong>:number</summary>
733733

734-
The field under this rule must have a size lower or equal than the given number.
734+
The field under this rule must have a size lower or equal than the given number.
735735
Value size calculated in same way like `min` rule.
736736

737737
You can also validate uploaded file using this rule to validate maximum size of uploaded file.
@@ -749,7 +749,7 @@ $validation = $validator->validate([
749749

750750
<details><summary><strong>between</strong>:min,max</summary>
751751

752-
The field under this rule must have a size between min and max params.
752+
The field under this rule must have a size between min and max params.
753753
Value size calculated in same way like `min` and `max` rule.
754754

755755
You can also validate uploaded file using this rule to validate size of uploaded file.
@@ -797,7 +797,7 @@ $validation = $validator->validate($inputs, [
797797
]);
798798
```
799799

800-
> For common URL scheme and mailto, we combine `FILTER_VALIDATE_URL` to validate URL format and `preg_match` to validate it's scheme.
800+
> For common URL scheme and mailto, we combine `FILTER_VALIDATE_URL` to validate URL format and `preg_match` to validate it's scheme.
801801
Except for JDBC URL, currently it just check a valid JDBC scheme.
802802

803803
</details>
@@ -807,6 +807,12 @@ The field under t rule must be integer.
807807

808808
</details>
809809

810+
<details><summary><strong>boolean</strong></summary>
811+
812+
The field under this rule must be boolean. Accepted input are `true`, `false`, `1`, `0`, `"1"`, and `"0"`.
813+
814+
</details>
815+
810816
<details><summary><strong>ip</strong></summary>
811817

812818
The field under this rule must be valid ipv4 or ipv6.
@@ -911,7 +917,7 @@ $validation = $validator->validate($_POST, [
911917
]);
912918
```
913919

914-
You can set invalid message by returning a string.
920+
You can set invalid message by returning a string.
915921
For example, example above would be:
916922

917923
```php
@@ -931,7 +937,7 @@ $validation = $validator->validate($_POST, [
931937
]);
932938
```
933939

934-
> Note: `Rakit\Validation\Rules\Callback` instance is binded into your Closure.
940+
> Note: `Rakit\Validation\Rules\Callback` instance is binded into your Closure.
935941
So you can access rule properties and methods using `$this`.
936942

937943
</details>
@@ -944,10 +950,10 @@ Field under this rule may be empty.
944950

945951
## Register/Override Rule
946952

947-
Another way to use custom validation rule is to create a class extending `Rakit\Validation\Rule`.
953+
Another way to use custom validation rule is to create a class extending `Rakit\Validation\Rule`.
948954
Then register it using `setValidator` or `addValidator`.
949955

950-
For example, you want to create `unique` validator that check field availability from database.
956+
For example, you want to create `unique` validator that check field availability from database.
951957

952958
First, lets create `UniqueRule` class:
953959

@@ -959,36 +965,36 @@ use Rakit\Validation\Rule;
959965
class UniqueRule extends Rule
960966
{
961967
protected $message = ":attribute :value has been used";
962-
968+
963969
protected $fillableParams = ['table', 'column', 'except'];
964-
970+
965971
protected $pdo;
966-
972+
967973
public function __construct(PDO $pdo)
968974
{
969975
$this->pdo = $pdo;
970976
}
971-
977+
972978
public function check($value): bool
973979
{
974980
// make sure required parameters exists
975981
$this->requireParameters(['table', 'column']);
976-
982+
977983
// getting parameters
978984
$column = $this->parameter('column');
979985
$table = $this->parameter('table');
980986
$except = $this->parameter('except');
981-
987+
982988
if ($except AND $except == $value) {
983989
return true;
984990
}
985-
991+
986992
// do query
987993
$stmt = $this->pdo->prepare("select count(*) as count from `{$table}` where `{$column}` = :value");
988994
$stmt->bindParam(':value', $value);
989995
$stmt->execute();
990996
$data = $stmt->fetch(PDO::FETCH_ASSOC);
991-
997+
992998
// true for valid, false for invalid
993999
return intval($data['count']) === 0;
9941000
}
@@ -1022,7 +1028,7 @@ $params['column'] = 'email';
10221028
$params['except'] = 'exception@mail.com';
10231029
```
10241030

1025-
> If you want your custom rule accept parameter list like `in`,`not_in`, or `uploaded_file` rules,
1031+
> If you want your custom rule accept parameter list like `in`,`not_in`, or `uploaded_file` rules,
10261032
you just need to override `fillParameters(array $params)` method in your custom rule class.
10271033

10281034
Note that `unique` rule that we created above also can be used like this:
@@ -1046,25 +1052,25 @@ use Rakit\Validation\Rule;
10461052
class UniqueRule extends Rule
10471053
{
10481054
...
1049-
1055+
10501056
public function table($table)
10511057
{
10521058
$this->params['table'] = $table;
10531059
return $this;
10541060
}
1055-
1061+
10561062
public function column($column)
10571063
{
10581064
$this->params['column'] = $column;
10591065
return $this;
10601066
}
1061-
1067+
10621068
public function except($value)
10631069
{
10641070
$this->params['except'] = $value;
10651071
return $this;
10661072
}
1067-
1073+
10681074
...
10691075
}
10701076

@@ -1098,11 +1104,11 @@ class YourCustomRule extends Rule
10981104
protected $implicit = true;
10991105

11001106
}
1101-
```
1107+
```
11021108

11031109
#### Modify Value
11041110

1105-
In some case, you may want your custom rule to be able to modify it's attribute value like our `default/defaults` rule. So in current and next rules checks, your modified value will be used.
1111+
In some case, you may want your custom rule to be able to modify it's attribute value like our `default/defaults` rule. So in current and next rules checks, your modified value will be used.
11061112

11071113
To do this, you should implements `Rakit\Validation\Rules\Interfaces\ModifyValue` and create method `modifyValue($value)` to your custom rule class.
11081114

src/Rules/Boolean.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php
2+
3+
namespace Rakit\Validation\Rules;
4+
5+
use Rakit\Validation\Rule;
6+
7+
class Boolean extends Rule
8+
{
9+
/** @var string */
10+
protected $message = "The :attribute must be a boolean";
11+
12+
/**
13+
* Check the value is valid
14+
*
15+
* @param mixed $value
16+
* @return bool
17+
* @throws \Exception
18+
*/
19+
public function check($value): bool
20+
{
21+
return \in_array($value, [\true, \false, "true", "false", 1, 0, "0", "1", "y", "n"], \true);
22+
}
23+
}

src/Validator.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ public function setValidator(string $key, Rule $rule)
5151
*/
5252
public function getValidator($key)
5353
{
54-
return isset($this->validators[$key])? $this->validators[$key] : null;
54+
return isset($this->validators[$key]) ? $this->validators[$key] : null;
5555
}
5656

5757
/**
@@ -137,6 +137,7 @@ protected function registerBaseValidators()
137137
'between' => new Rules\Between,
138138
'url' => new Rules\Url,
139139
'integer' => new Rules\Integer,
140+
'boolean' => new Rules\Boolean,
140141
'ip' => new Rules\Ip,
141142
'ipv4' => new Rules\Ipv4,
142143
'ipv6' => new Rules\Ipv6,

0 commit comments

Comments
 (0)