Calibrate hex and rgba colors using regex in php

text field

I am using Laravel and I am trying to check the color field. This text field should allow only the colors HEX, rgb, rgba, hsland hsla, using a regular expression pattern.

In my controller, I have this template, but it does not confirm my field value. Any line will be tested.

$this->validate($request, [
    'color' => [
        'required',
        'regex:/(#(?:[0-9a-f]{2}){2,4}|#[0-9a-f]{3}|(?:rgba?|hsla?)\((?:\d+%?(?:deg|rad|grad|turn)?(?:,|\s)+){2,3}[\s\/]*[\d\.]+%?\))/i', // <--- not working
    ],
]);

Thank.

+4
source share
2 answers

You must add the anchors ( ^and $):

'regex:/^(#(?:[0-9a-f]{2}){2,4}|#[0-9a-f]{3}|(?:rgba?|hsla?)\((?:\d+%?(?:deg|rad|grad|turn)?(?:,|\s)+){2,3}[\s\/]*[\d\.]+%?\))$/i',
        ^                                                                                                                     ^

That the regular expression was applied to all input, but not just corresponded to it.

, rgba(1024, 1023, 0), .


, (demo):

^(\#[\da-f]{3}|\#[\da-f]{6}|rgba\(((\d{1,2}|1\d\d|2([0-4]\d|5[0-5]))\s*,\s*){2}((\d{1,2}|1\d\d|2([0-4]\d|5[0-5]))\s*)(,\s*(0\.\d+|1))\)|hsla\(\s*((\d{1,2}|[1-2]\d{2}|3([0-5]\d|60)))\s*,\s*((\d{1,2}|100)\s*%)\s*,\s*((\d{1,2}|100)\s*%)(,\s*(0\.\d+|1))\)|rgb\(((\d{1,2}|1\d\d|2([0-4]\d|5[0-5]))\s*,\s*){2}((\d{1,2}|1\d\d|2([0-4]\d|5[0-5]))\s*)|hsl\(\s*((\d{1,2}|[1-2]\d{2}|3([0-5]\d|60)))\s*,\s*((\d{1,2}|100)\s*%)\s*,\s*((\d{1,2}|100)\s*%)\))$
+5

, . ,

1. #[a-zA-Z0-9]{6} , #090f00

2. rgb\((?:\s*\d+\s*,){2}\s*[\d]+\) , rgb(10, 10, 20)

3. rgba\((\s*\d+\s*,){3}[\d\.]+\) rgba(100,100,100,0.9)

4. hsl\(\s*\d+\s*(\s*\,\s*\d+\%){2}\) , hsl(10,30%,40%)

5. hsla\(\s*\d+(\s*,\s*\d+\s*\%){2}\s*\,\s*[\d\.]+\) , hsla(120, 60%, 70%, 0.3)

Regex:

#[a-zA-Z0-9]{6}|rgb\((?:\s*\d+\s*,){2}\s*[\d]+\)|rgba\((\s*\d+\s*,){3}[\d\.]+\)|hsl\(\s*\d+\s*(\s*\,\s*\d+\%){2}\)|hsla\(\s*\d+(\s*,\s*\d+\s*\%){2}\s*\,\s*[\d\.]+\)

- Regex

+3

Source: https://habr.com/ru/post/1676022/


All Articles