Laravel OR验证URL或IP

时间:2019-06-16 16:54:56

标签: php regex laravel validation laravel-validation

我有一个表单字段,我想验证输入的值是有效的URL还是IP地址。

我创建了一个自定义表单请求验证来验证url(laravel提供的可用url验证还不够),并且效果很好。

但是如何更改验证以检查它是有效的URL还是有效的ip?只有在两个验证都失败的情况下,它才应该失败。

<?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})?(\/.*)?$^'
            ]
        ];
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用this正则表达式

^(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])$

您的代码最终应该像这样:

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])$']
    ];
}