Last active
June 3, 2019 08:57
-
-
Save spresnac/03664babffabb4e006dbab1ce126b709 to your computer and use it in GitHub Desktop.
A rule to check passing boolean-like values in validation requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Rules; | |
use Illuminate\Contracts\Validation\Rule; | |
/** | |
* Class RealBoolean | |
* | |
* To check on several values that can be interpreted as 'boolean' | |
* | |
* @package App\Rules | |
*/ | |
class RealBoolean implements Rule | |
{ | |
/** | |
* Create a new rule instance. | |
* | |
* @return void | |
*/ | |
public function __construct() | |
{ | |
// | |
} | |
/** | |
* Determine if the validation rule passes. | |
* | |
* @param string $attribute | |
* @param mixed $value | |
* @return bool | |
*/ | |
public function passes($attribute, $value) : bool | |
{ | |
if ($value === true || $value === false) { | |
return true; | |
} | |
$accept = [0, 1, '0', '1', 'true', 'false', 'j', 'n']; | |
return in_array(strtolower($value), $accept, true); | |
} | |
/** | |
* Get the validation error message. | |
* | |
* @return string | |
*/ | |
public function message() : string | |
{ | |
return 'The :attribute must be a boolean value'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment