Laravel验证,其中“-”分隔为IP

时间:2018-09-01 18:47:43

标签: laravel validation

我想在表单字段中输入IP范围。像192.168.1.3-192.168.1.254

我该如何验证

这是我的代码

HTML

<div class="form-group row">
    <label class="col-2 col-form-label">Pool IP Range</label>

    <input type="text" class="form-control" name="range_ip" value="" placeholder="Enter Pool IP (192.168.1.2-192.168.1.254)">

</div>

控制器:

public function store(Request $request)
    {
    $validate = [
        'pool_name' => 'required|unique:pools|max:10',
        'server_id' => 'required'
    ];

    $ips = explode('-', $request['range_ip']);
    foreach ($ips as $ip) {
        $validate['range_ip'] = $ip;
    }


    $this->validate($request, $validate);
}

1 个答案:

答案 0 :(得分:0)

下面的代码,还请确保first ip <second ip

public function store(Request $request)
{
    $this->validate($request, [
        'pool_name' => 'required|unique:pools|max:10',
        'server_id' => 'required',
        'range_ip' => [
            'required',
            function($attribute, $value, $fail) {
                $validIp = array_filter(explode('-', $value), function($ip) {
                                return filter_var($ip, FILTER_VALIDATE_IP);
                        });

                if ( (count($validIp) !== 2) || (ip2long($validIp[0]) >= ip2long($validIp[1])) )
                {
                    return $fail($attribute.' is invalid.');
                }
            },
        ],
    ]);
}