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);
}
2
  • laravel.com/docs/5.7/validation#custom-validation-rules Just read the docs Commented Feb 7, 2019 at 7:42
  • @Markus: I have read that but I am unable to convert this into the custom validator. Commented Feb 7, 2019 at 7:43

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the url validator of laravel

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

1 Comment

The field under validation must be a valid URL. - localhost is a valid URL, so I don't think this will work.
1

You can use

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

I hope this will be useful

Comments

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);

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.