How to Use the ValidUrl Rule from Laravel-Validate
The ValidUrl rule validates HTTP and HTTPS URLs using a regular expression that accepts optional www. prefixes and standard domain characters, implementing Laravel's Rule contract to return a translatable error message when validation fails.
The ValidUrl rule is a custom validation rule provided by the milwad-dev/laravel-validate package that extends Laravel's validation capabilities with robust URL checking. This rule integrates seamlessly with form requests, controllers, and manual validator instances by implementing the Illuminate\Contracts\Validation\Rule interface. According to the source code in src/Rules/ValidUrl.php, the rule uses regex pattern matching to ensure URLs follow proper HTTP/HTTPS formatting before passing validation.
Understanding the ValidUrl Implementation
The ValidUrl class resides in src/Rules/ValidUrl.php and adheres strictly to Laravel's validation contract, requiring two core methods that define its behavior.
The passes() Validation Method
The passes($attribute, $value): bool method contains the core validation logic. It validates the input string against a regular expression designed to match typical HTTP and HTTPS URLs, allowing optional www. subdomains and a comprehensive set of characters in the domain and path segments. This method returns true only when the provided value conforms to standard URL formatting rules.
The message() Localization Method
The message(): string method returns the error message identifier validate.url. When validation fails, Laravel's translation system searches for this key within your application's language files (typically resources/lang/en/validate.php) to display the appropriate error message to users.
How to Use the ValidUrl Rule in Your Application
Because the rule follows Laravel's standard contract, you can instantiate it anywhere the framework expects a validation rule instance.
Basic Usage in Controllers or Form Requests
Apply the rule within your validation arrays by instantiating the ValidUrl class directly:
<?php
use Milwad\LaravelValidate\Rules\ValidUrl;
$rules = [
'website' => ['required', new ValidUrl],
];
$payload = ['website' => 'https://www.example.com'];
$validator = validator($payload, $rules);
if ($validator->fails()) {
$errors = $validator->errors()->all(); // ['The website format is invalid.']
}
Manual Validator Instances
As demonstrated in tests/Rules/ValidUrlTest.php, you can validate data programmatically using the validator's make method:
<?php
use Milwad\LaravelValidate\Rules\ValidUrl;
$rules = ['url' => [new ValidUrl]];
$data = ['url' => 'https://github.com/milwad-dev'];
$passes = app('validator')->make($data, $rules)->passes(); // true
Customizing Error Messages
You can override the default validation message by adding a custom closure or modifying your translation files. For attribute-specific customization within your validation logic:
<?php
use Milwad\LaravelValidate\Rules\ValidUrl;
$rules = [
'homepage' => [
'required',
new ValidUrl,
function ($attribute, $value, $fail) {
if (!preg_match('/^https?:\/\/.+$/', $value)) {
$fail('The :attribute must start with http:// or https://');
}
},
],
];
Testing and Validation Behavior
The package includes comprehensive test coverage in tests/Rules/ValidUrlTest.php that verifies the rule correctly accepts valid URLs (including those with complex query strings and paths) while rejecting malformed strings. The documentation at docs/1.x/valid-url.md provides additional implementation details and edge-case handling for developers implementing this validation rule in production environments.
Summary
- The ValidUrl rule validates HTTP/HTTPS URLs using regex pattern matching implemented in
src/Rules/ValidUrl.php. - It implements the
Illuminate\Contracts\Validation\Ruleinterface withpasses()andmessage()methods. - The rule returns the translation key
validate.urlfor error messages, which you can customize via Laravel's localization files. - You can use the rule in form requests, controller validation, or manual validator calls by instantiating
new ValidUrl. - The package provides test coverage in
tests/Rules/ValidUrlTest.phpand documentation atdocs/1.x/valid-url.md.
Frequently Asked Questions
What URL formats does the ValidUrl rule accept?
The ValidUrl rule accepts standard HTTP and HTTPS URLs, including those with optional www. prefixes, domain names, IP addresses, ports, paths, and query strings. The validation logic uses a comprehensive regular expression defined in src/Rules/ValidUrl.php to ensure the URL structure conforms to RFC standards while remaining flexible enough for common web addresses.
How do I customize the error message for the ValidUrl rule?
The rule returns the translation key validate.url through its message() method. You can customize this message by adding the key to your language files (e.g., resources/lang/en/validate.php) or by appending a custom validation closure to your rules array that provides specific error text for the failing attribute.
Can I use ValidUrl in Laravel form requests?
Yes, the ValidUrl rule works seamlessly in form request classes because it implements the Illuminate\Contracts\Validation\Rule contract. Simply import Milwad\LaravelValidate\Rules\ValidUrl and include new ValidUrl in your form request's rules() method array, exactly as you would in a controller.
Where is the ValidUrl rule source code located?
The implementation resides in src/Rules/ValidUrl.php within the milwad-dev/laravel-validate repository. Additional usage documentation is available at docs/1.x/valid-url.md, and the test suite demonstrating expected behavior is located at tests/Rules/ValidUrlTest.php.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →