Skip to content

Instantly share code, notes, and snippets.

@devhammed
Created November 17, 2026 12:05
Show Gist options
  • Select an option

  • Save devhammed/575e1f114a83e7d2d9b9983d79508581 to your computer and use it in GitHub Desktop.

Select an option

Save devhammed/575e1f114a83e7d2d9b9983d79508581 to your computer and use it in GitHub Desktop.
Laravel XPath Validation Rule
<?php
declare(strict_types=1);
namespace App\Rules;
use Closure;
use Dom\XPath;
use Throwable;
use Dom\HTMLDocument;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Translation\PotentiallyTranslatedString;
class XpathRule 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->isValidXpath($value)) {
$fail('validation.xpath')->translate();
}
}
/**
* Check if a string is a valid XPath expression.
*/
protected function isValidXpath(string $value): bool
{
try {
$doc = HTMLDocument::createFromString('<h1>Laravel</h1>', LIBXML_NOERROR);
$xpath = new XPath($doc);
$xpath->evaluate($value);
return true;
} catch (Throwable) {
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment