Created
November 17, 2026 12:05
-
-
Save devhammed/575e1f114a83e7d2d9b9983d79508581 to your computer and use it in GitHub Desktop.
Laravel XPath 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 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