mirror of
https://github.com/Respect/Validation.git
synced 2026-03-16 15:25:45 +01:00
This validator is made to validate numbers in any base, even with custom bases
It also have a shortcut, you can use something like
v::base3()->assert('0212');
instead of
v::base(3)->assert('0212');
You can also use custom numeric sequences, like
v::base(3, 'xy')->assert('xyxyx');
34 lines
808 B
PHP
34 lines
808 B
PHP
<?php
|
|
|
|
namespace Respect\Validation\Rules;
|
|
|
|
use Respect\Validation\Exceptions\BaseException;
|
|
|
|
class Base extends AbstractRule
|
|
{
|
|
|
|
public $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
|
public $base;
|
|
|
|
public function __construct($base=null, $chars=null)
|
|
{
|
|
if (!is_null($chars)) $this->chars = $chars;
|
|
|
|
$max = strlen($this->chars);
|
|
if (!is_numeric($base) || $base > $max)
|
|
throw new BaseException(
|
|
sprintf(
|
|
'a base between 1 and %s is required', $max
|
|
)
|
|
);
|
|
$this->base = $base;
|
|
}
|
|
|
|
public function validate($input)
|
|
{
|
|
$valid = substr($this->chars, 0, $this->base);
|
|
return (boolean)preg_match("@^[$valid]+$@", (string)$input);
|
|
}
|
|
|
|
}
|
|
|