Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel eloquent rule for domain name

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.

like image 480
CrazyWu Avatar asked Nov 05 '17 13:11

CrazyWu


1 Answers

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',
    ],
]);
like image 57
Robert Avatar answered Oct 16 '22 23:10

Robert