Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lat4732's avatar
Level 12

Is this regex rule valid for validating domain name in 2022?

I have a simple question - Is this regex rule actual for validating domain name in 2022?

/(?P<domain>[a-z0-9][a-z0-9\-]{0,63}\.[a-z\.]{1,5})$/i

If it's not OK for validating domain name in 2022, then how do I rebuild it to achieve correct validating rule?

0 likes
5 replies
Niush's avatar

That is good enough but not perfect. For example, it does not work for "my-school.edu.np".

Instead, you could use PHP's own filtering, combined with Laravel validation.

First create custom validation rule in Laravel. https://laravel.com/docs/9.x/validation#custom-validation-rules

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
 
class ValidDomain implements Rule
{
    
    public function passes($attribute, $value)
    {
        return filter_var($value, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME)
          ? true
          : false;
    }
 
    
    public function message()
    {
        return 'The :attribute must be a valid domain.';
    }
}

Then you could validate with:

use App\Rules\ValidDomain;

$request->validate([
    'domain' => ['required', new ValidDomain, 'url', 'active_url'],
]);

The url and active_url is also explained in the doc. https://laravel.com/docs/9.x/validation

I have not tested the code above. But the gist is similar.

1 like
lat4732's avatar
Level 12

@Niush Thanks for your answer. Honestly, that didn't seem perfect to me either. I also don't want to change the way I do things. I just want a regular expression rule that matches the 2022 domain name policy.

lat4732's avatar
Level 12

I'm still looking for the most effective regex rule for catching the real domain name. The provided string that must be filtered is actually a result of PHP parse_url($url, PHP_URL_HOST). It actually returns the domain name but with subdomains. I need a rule to remove the subdomains and return only the real domain name. EVERY HELP IS APPRECIATED!!

Sinnbeck's avatar

Why not just check if the domain exists?

Please or to participate in this conversation.