1

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);
}
Yoram de Langen
  • 5,391
  • 3
  • 24
  • 31
  • https://laravel.com/docs/5.7/validation#custom-validation-rules Just read the docs – Markus Feb 07 '19 at 07:42
  • @Markus: I have read that but I am unable to convert this into the custom validator. –  Feb 07 '19 at 07:43

5 Answers5

3

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.

Yoram de Langen
  • 5,391
  • 3
  • 24
  • 31
1

You can use the url validator of laravel

https://laravel.com/docs/5.2/validation#rule-url

dns_nx
  • 3,651
  • 4
  • 37
  • 66
  • 1
    `The field under validation must be a valid URL.` - `localhost` is a valid URL, so I don't think this will work. – Don't Panic Feb 07 '19 at 17:11
1

You can use

'url'   => ['regex' => '/^((?:https?\:\/\/|www\.)(?:[-a-z0-9]+\.)*[-a-z0-9]+.*)$/'],

I hope this will be useful

Rohit Suthar
  • 3,528
  • 1
  • 42
  • 48
Sandy Sanap
  • 755
  • 1
  • 5
  • 17
0
$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);
0

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.

Reference Here

MugoTech
  • 11
  • 3