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,153
  • 3
  • 23
  • 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

4 Answers4

2

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,153
  • 3
  • 23
  • 31
1

You can use the url validator of laravel

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

dns_nx
  • 3,190
  • 4
  • 31
  • 55
  • `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,483
  • 1
  • 38
  • 47
Sandy Sanap
  • 745
  • 5
  • 15
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);