user3382438
user3382438

Reputation: 131

Laravel OR Validation URL or IP

I have a form field and I want to validate if the entered value is a valid url OR a IP Address.

I have created a custom form request validation to validate the url (the available url validation from laravel was not enough) and that works fine.

But how can I change my Validation to check if it is an valid url or valid ip? It should only fail if both validation fails.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CheckDomain extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * 
     * Manipulate Input Domain before Validation
     *
     */
    protected function prepareForValidation()
    {
        // Remove HTTP - HTTPS
        $this->domain = str_replace([
                            'http://', 'https://'
                        ], '', $this->domain);

        $this->domain = strtok($this->domain, '/'); // Remove Slashes
        $this->domain = strtolower($this->domain); // Make Lowercase

        // Bring Together
        $this->merge([
            'domain' => $this->domain
        ]); 
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'domain' => [
                'required', 'regex:^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$^'
            ]
        ];
    }
}

Upvotes: 1

Views: 3414

Answers (1)

Erkan &#214;zk&#246;k
Erkan &#214;zk&#246;k

Reputation: 891

You can use this regex

^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?|^((http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$

And your code finally should be like:

public function rules()
{
    return [
        'domain' => ['required', 'regex:^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?|^((http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$']
    ];
}

Upvotes: 1

Related Questions