Skip to content

Instantly share code, notes, and snippets.

@devhammed
Created July 8, 2026 20:23
Show Gist options
  • Select an option

  • Save devhammed/68329f263a52a35ea4ec4a17510554db to your computer and use it in GitHub Desktop.

Select an option

Save devhammed/68329f263a52a35ea4ec4a17510554db to your computer and use it in GitHub Desktop.
Laravel CSS Selector Validation Rule
<?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