Created
July 8, 2026 20:23
-
-
Save devhammed/68329f263a52a35ea4ec4a17510554db to your computer and use it in GitHub Desktop.
Laravel CSS Selector Validation Rule
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 | |
| declare(strict_types=1); | |
| namespace App\Rules; | |
| use Closure; | |
| use DOMException; | |
| use Dom\HTMLDocument; | |
| use Illuminate\Contracts\Validation\ValidationRule; | |
| use Illuminate\Translation\PotentiallyTranslatedString; | |
| class CssSelectorRule implements ValidationRule | |
| { | |
| /** | |
| * Run the validation rule. | |
| * | |
| * @param Closure(string, ?string=): PotentiallyTranslatedString $fail | |
| */ | |
| public function validate(string $attribute, mixed $value, Closure $fail): void | |
| { | |
| if (! is_string($value) || ! $this->isValidCssSelector($value)) { | |
| $fail('validation.css_selector')->translate(); | |
| } | |
| } | |
| /** | |
| * Check if a string is a valid CSS selector. | |
| */ | |
| protected function isValidCssSelector(string $value): bool | |
| { | |
| try { | |
| $doc = HTMLDocument::createFromString('<!DOCTYPE html><html lang="en"><body>Laravel forever!</body></html>'); | |
| $doc->querySelector($value); | |
| return true; | |
| } catch (DOMException) { | |
| return false; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment