Reputation:
I'am trying to validate a URL to make sure it doesn't contain localhost. I have done it using if-else and want to do it using custom validator. I am lost how it could be done by validator.
if((strpos($request->input('url'), 'localhost') !== false) ||
(strpos($request->input('url'), 'http://localhost') !== false) ||
(strpos($request->input('url'), 'https://localhost') !== false) ||
(strpos($request->input('url'), '127.0.0.1') !== false) ||
(strpos($request->input('url'), 'http://127.0.0.1') !== false) ||
(strpos($request->input('url'), 'http://127.0.0.1') !== false))
{
return response()->json([
'error_description' => 'Localhost in not allowed in URL'
], 403);
}
Upvotes: 1
Views: 16371
Reputation: 11
You can make use of active_url
rule that checks if a url has existing A or AAAA records and is reachable. localhost won't validate true in this case.
Upvotes: 0
Reputation: 1
$messages = [
'url.required' => 'Đường dẫn bắt buộc nhập',
'url.url' => 'Url không hợp lệ'
];
$data = request()->validate([
'url' => 'required|url',
], $messages);
Upvotes: 0
Reputation: 753
You can use
'url' => ['regex' => '/^((?:https?\:\/\/|www\.)(?:[-a-z0-9]+\.)*[-a-z0-9]+.*)$/'],
I hope this will be useful
Upvotes: 1
Reputation: 5499
You can already achieve it with existing validation and a regex:
'url' => 'regex:/^http:\/\/\w+(\.\w+)*(:[0-9]+)?\/?$/',
I did not test this, but it is creative with existing validation rules.
Upvotes: 3
Reputation: 3943
You can use the url
validator of laravel
https://laravel.com/docs/5.2/validation#rule-url
Upvotes: 1