【问题标题】:Laravel 5 Validation accept comma separated string with max 4 numbersLaravel 5 验证接受逗号分隔的字符串,最多 4 个数字
【发布时间】:2019-10-03 11:00:46
【问题描述】:

Laravel 5 验证接受逗号分隔的字符串,最多 4 个数字

例子-

1.  1,2,3,4              ---  Accepted

2.  1,2                  ---  Accepted

3.  1,2,3,4,5            ---  Rejected

注意:我可以通过首先将字符串转换为数组然后验证请求来完成此任务,但我正在寻找解决相同问题的最佳方法。

【问题讨论】:

  • 很高兴知道这一点。
  • 不知道怎么做,同样帮助我

标签: laravel laravel-5 laravel-5.2 laravel-validation


【解决方案1】:

您可以为此创建自己的custom Rule

php artisan make:rule MaxNumbers
<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class MaxNumbers implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return count(explode(',', $value)) < 5;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be max 4 numbers.';
    }
}

并使用它:

use App\Rules\MaxNumbers;

$request->validate([
    'field_name' => ['required', new MaxNumbers],
]);

【讨论】:

  • 一些正则表达式来检查实际数字不会造成伤害
  • 自定义验证是否在 Laravel 5.6 中?
  • 不,5.2也是,你可以找到更多here
【解决方案2】:

在你的控制器中用这个验证它:

$this->validate(Request::instance(), ['field_name'=>['required','regex:/^\d+(((,\d+)?,\d+)?,\d+)?$/']]);

【讨论】:

    【解决方案3】:

    您可以使用以下正则表达式规则:

    $this->validate($request, [
        'field_name' => 'regex:/^[0-9]+(,[0-9]+){0,3}$/'
    ]);
    

    【讨论】:

      猜你喜欢
      • 2018-03-18
      • 2019-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-05
      相关资源
      最近更新 更多