Skip to content

Commit b1c145c

Browse files
committed
Add rule DivisibleBy
1 parent 149d746 commit b1c145c

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

resources/lang/en/validation.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
'btc_address' => 'The :attribute must be a valid BTC address.',
1010
'credit_card' => 'The :attribute must be a valid credit card number.',
1111
'data_uri' => 'The :attribute must have data uri format.',
12+
'divisible_by' => 'The :attribute must be divisible by :number.',
1213
'float_number' => 'The :attribute must be a float number',
1314
'image_url' => 'The :attribute must be a valid image URL.',
1415
'phone' => 'The :attribute must be a valid phone number.',

src/Rules/DivisibleBy.php

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
<?php
2+
3+
namespace Arifszn\AdvancedValidation\Rules;
4+
5+
use Illuminate\Contracts\Validation\Rule;
6+
7+
/**
8+
* The field under validation must be divisible by another.
9+
*
10+
* @package Arifszn\AdvancedValidation\Rules
11+
*/
12+
class DivisibleBy implements Rule
13+
{
14+
/**
15+
* @var string
16+
*/
17+
private $errorMessage;
18+
19+
/**
20+
* @var int
21+
*/
22+
private $number;
23+
24+
/**
25+
* @var string
26+
*/
27+
private $attribute;
28+
29+
/**
30+
* Create a new rule instance.
31+
*
32+
* @param int $number Divisible by number.
33+
* @param string|null $errorMessage Custom error message.
34+
* @return void
35+
*/
36+
public function __construct(int $number, string $errorMessage = null)
37+
{
38+
$this->number = $number;
39+
$this->errorMessage = $errorMessage;
40+
}
41+
42+
/**
43+
* Determine if the validation rule passes.
44+
*
45+
* @param string $attribute
46+
* @param mixed $value
47+
* @return bool
48+
*/
49+
public function passes($attribute, $value)
50+
{
51+
$this->attribute = $attribute;
52+
53+
return (floatval($value) !== 0.0) && (floatval($value) % intval($this->number, 10) === 0);
54+
}
55+
56+
/**
57+
* Get the validation error message.
58+
*
59+
* @return string
60+
*/
61+
public function message()
62+
{
63+
return $this->errorMessage ? $this->errorMessage : trans('advancedValidation::validation.divisible_by', [
64+
'attribute' => $this->attribute,
65+
'number' => $this->number
66+
]);
67+
}
68+
}

0 commit comments

Comments
 (0)