Is there any specific rule for domain names? I was googling for about an hour but didn't get the list of rules.
I've tried "domain" => "required|url"
, but it requires a protocol type in it, so it's not the best option for me.
I use a custom rule to check for valid FQDN.
Got the regex from another answer here @ SO, see: fully-qualified-domain-name-validation
One of the answers provides a regex, with example:
/^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){1,127}(?![0-9]*$)[a-z0-9-]+\.?)$/i
With a demo: http://regexr.com/3g5j0 which shows you the matches.
Laravel 5.5
I then created a custom rule:
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class FQDN implements Rule
{
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
return preg_match('/^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){1,127}(?![0-9]*$)[a-z0-9-]+\.?)$/i', $value);
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'Invalid FQDN.';
}
}
And used it like this:
// ...
use App\Rules\FQDN;
// ...
$this->validate($request, [
// other rules be here
'fqdn' => [
'required',
new FQDN(),
],
]);
Edit for Laravel 5.4
In Laravel 5.4 you do not have the Rule contract, you can extend the validator in the AppServiceProvider, see here (or create a separate ExtendedValidationServiceProvider).
You can do this inline, but I prefer having separate classes for this.
In the ServiceProvider boot method, add:
use Illuminate\Support\Facades\Validator;
// ...
public function boot()
{
Validator::extend('fqdn', 'App\Rules\FQDN@validate');
Validator::replacer('fqdn', 'App\Rules\FQDN@replace');
}
Validator::extend()
is for the validation rule
Validator::replacer()
is for the error message
Then for the 5.4 rule class:
<?php
namespace App\Rules;
class FQDN
{
public function validate($attribute, $value, $parameters, $validator)
{
return preg_match('/^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){1,127}(?![0-9]*$)[a-z0-9-]+\.?)$/i', $value);
}
public function replace($message, $attribute, $rule, $parameters)
{
return str_replace(':fqdn', implode(', ', $parameters), $message);
}
}
Now you can use your validation like:
$this->validate($request, [
// other rules be here
'fqdn' => [
'required',
'fqdn',
],
]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With