8

Laravel URL Validation Rule Example

 1 year ago
source link: https://www.laravelcode.com/post/laravel-url-validation-rule-example
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Laravel URL Validation Rule Example

  1377 views

  8 months ago

Laravel

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://laravelcode.com/posts';

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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK