Laravel 8 url validation example

Sometimes you may want to validate url into your Laravel application. This is helpful in preventing user input invalid url data.

In this example, we will see how you can validate url field into Laravel application. There are two ways you can validate URL into Laravel application. You can either use regular expression or Laravel url validation rules. We will see both validation with example.

Validation using regular expression(regex)

The first way, you can validate url using regex. This method also validate url even if url not contains http:// or https://. Let's see example:

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $regex = '/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/';

    $input = $request->validate([
        'url' => 'required|regex:'.$regex,
    ]);

    dd($input['url']); // print input url
}

Validate using url validation rule

Laravel provides many default validation rules. For example 'required' validation rule checks that field shouldn't be null. url validation rule checks that field should be url. Let's see its example:

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $input = $request->validate([
        'url' => 'required|url'
    ]);

    dd($input['url']); // print input url
}

Validate using filter_var($url, FILTER_VALIDATE_URL) method

Sometimes you may want to validate url other than form submit. In this situation, you can also use filter_var() method with FILTER_VALIDATE_URL option. You can use this method in any PHP application. Laravel uses filter_var() method to validate url into request object. Let's see its example:

$url = 'https://hackthestuff.com/url-encode';

if(filter_var($url, FILTER_VALIDATE_URL)) {
    echo('The url is valid');
} else {
    echo('The url is not valid');
}

So, these are the ways you can validate url into Laravel application. Thank for reading the article.

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

No Comment