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

speedydan's avatar

Using RegEx validation rule

This might be a really silly question...

But I have the following regular expression that highlights any url in a block of text:

/(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[A-Z0-9+&@#\/%=~_|$])/igm

And i'm wondering how I'd use this as a validation rule - the ending /igm seems to be causing issues - but I need them as part of the rule.

0 likes
3 replies
Cronix's avatar

What is your actual goal, in terms of validation? Are you just trying to see if a piece of text contains a link, or multiple links? What are you testing for?

speedydan's avatar

Hey @cronix - I have a textarea on a form, a bio basically - but I don't want users to be able to include any anchor tags with links in.

Cronix's avatar

You will have to create a custom rule for that. The rule would use regex and just return true/false if it passes (no links contained in text). There is no g modifier for preg_match, which I believe is what laravel is running the regex through behind the scenes.

You could just do something like this and create a custom rule with a closure. https://laravel.com/docs/5.8/validation#using-closures

$validator = Validator::make($request->all(), [
    'title' => [
        'required',
        'max:255',
        function ($attribute, $value, $fail) {
            if (preg_match('/(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[A-Z0-9+&@#\/%=~_|$])/im', $value, $matches)) {
            
                $fail($attribute.' cannot contain links.');
            }
        },
    ],
]);

something like that (can't test atm).

Please or to participate in this conversation.