验证 Laravel 中 2 个数字的幂

validate power of 2 numbers in Laravel

我如何验证 1 到 1000 之间的数字是 2 的幂?

public function rules()
{
  return [
   'threshold' => 'required'|between:1,1000|power??
  ];
}

您可以在验证中使用闭包:

public function rules()
    {
        return [
            'threshold' => [
                'required',
                'between:1,1000',
                function ($attribute, $value, $fail) {
                    if ($value == 0 || ($value & ($value - 1)) != 0) {
                        $fail($attribute . ' is not power of 2!');
                    }
                },
            ]
        ];
    }

参见 laravel 文档 => Validation

您可以为此创建一个新的 Rule object

例如:

class PowerOfTwo implements Illuminate\Contracts\Validation\Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return ($value & ($value - 1)) == 0;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be a power of 2.';
    }
}

要使用上述规则,您需要执行以下操作:

$data = [
    'threshold' => 256  
];

$rules = [
    'threshold' => ['required', 'integer', 'between:1,1000', new PowerOfTwo]
];

$validator = Validator::make($data, $rules);     

如果你想测试你的数字是否在 1 到 1000 之间,你还需要添加 integer 规则。

这里有一个 example 你可以玩。