/
HexColorValidator.php
executable file
·48 lines (42 loc) · 1.17 KB
/
HexColorValidator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?php
namespace Oh\ColorPickerTypeBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class HexColorValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
/**
* Valid:
*
* #ffffff
* #ddd
* ffffff
* 444
*
* Invalid:
*
* #wsfsga
* #9999
* ggg
* gggggg
*/
if(is_null($constraint->requireHash))
{
$hashReg = '#{0,1}';
}else if ($constraint->requireHash === true)
{
$hashReg = '#';
}else if ($constraint->requireHash === false)
{
$hashReg = '';
}else {
throw new \Exception('The requireHash option value is invalid');
}
if (!preg_match("/^$hashReg([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/", $value)) {
$this->setMessage($constraint->message, array('%color%' => $value));
return false;
}
return true;
}
}